package com.qujia.station.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.qujia.common.annotation.Log;
import com.qujia.common.config.QuJiaConfig;
import com.qujia.common.constant.HttpStatus;
import com.qujia.common.constant.UserConstants;
import com.qujia.common.core.controller.BaseController;
import com.qujia.common.core.domain.AjaxResult;
import com.qujia.common.core.domain.ResultData;
import com.qujia.common.core.domain.entity.SysDept;
import com.qujia.common.core.domain.entity.SysRole;
import com.qujia.common.core.domain.entity.SysUser;
import com.qujia.common.core.domain.model.LoginUser;
import com.qujia.common.core.page.TableDataInfo;
import com.qujia.common.core.redis.RedisCache;
import com.qujia.common.enums.BusinessType;
import com.qujia.common.enums.PayTypeEnum;
import com.qujia.common.exception.CustomException;
import com.qujia.common.utils.DateUtils;
import com.qujia.common.utils.SecurityUtils;
import com.qujia.common.utils.poi.ExcelUtil;
import com.qujia.customer.domain.CustomerCardUseRecord;
import com.qujia.customer.mapper.ReductionActivityBalanceRecordMapper;
import com.qujia.customer.service.ICustomerCardUseRecordService;
import com.qujia.customer.service.ICustomerElectronicCardService;
import com.qujia.integral.service.ICustomerPointsRecordService;
import com.qujia.station.domain.*;
import com.qujia.station.domain.dto.DivideAccountsSettingDto;
import com.qujia.station.domain.dto.MemberNumDto;
import com.qujia.station.domain.dto.OilSaleNumDto;
import com.qujia.station.domain.form.PayOrderDetailQueryForm;
import com.qujia.station.domain.form.PayOrderEmployeeQueryForm;
import com.qujia.station.domain.vo.*;
import com.qujia.station.enums.EmployeeShowEnum;
import com.qujia.station.enums.PrintEnum;
import com.qujia.station.mapper.OilMapper;
import com.qujia.station.mapper.PresentAmountRecordMapper;
import com.qujia.station.service.*;
import com.qujia.station.utils.FeiEPrinterUtil;
import com.qujia.station.utils.StaffUtil;
import com.qujia.station.utils.YiLianYunPrinterUtil;
import com.qujia.system.domain.HttpUtils;
import com.qujia.system.domain.SysRespon;
import com.qujia.system.domain.XcxActualPaymentDto;
import com.qujia.system.service.IAppUserInfoUserService;
import com.qujia.system.service.ISysDeptService;
import com.qujia.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 订单支付Controller
 *
 * @author qujia
 * @date 2020-12-10
 */
@Api(tags = "订单相关接口", description = "订单相关接口")
@RestController
@RequestMapping("/station/order")
public class PayOrderController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(PayOrderController.class);
    @Autowired
    private IPayOrderService payOrderService;
    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private IPayOrderHistoryService payOrderHistoryService;
    @Autowired
    private IStationDeviceManageService stationDeviceManageService;

    @Autowired
    private IStationBalanceChangeService stationBalanceChangeService;
    @Autowired
    private IStationService stationService;


    @Autowired
    private ISysUserService userService;

    @Autowired
    private ICustomerCardUseRecordService customerCardUseRecordService;

    @Resource
    private OrderPrintService orderPrintService;

    @Resource
    private RedisCache redisCache;

    @Resource
    private InvoiceService invoiceService;

    @Autowired
    private MemberManagementService memberManagementService;

    @Autowired
    private TeamManagementService teamManagementService;

    @Autowired
    private IClassSettlementService classSettlementService;



    @Resource
    private IAppUserInfoUserService appUserInfoUserService;

    @Resource
    private IAppUserInfoService appUserInfoService;

    @Resource
    private ICustomerElectronicCardService customerElectronicCardService;

    @Resource
    private ICustomerPointsRecordService customerPointsRecordService;

    @Resource
    private IEnterpriseService enterpriseService;

    @Autowired
    private IPhysicalCardBalanceService physicalCardBalanceService;

    @Autowired
    private IPayOrderAllService payOrderAllService;

    @Resource
    private PresentAmountRecordMapper presentAmountRecordMapper;

    @Resource
    private OilMapper oilMapper;

    @Resource
    private ISysUserService sysUserService;

    @Resource
    private ReductionActivityBalanceRecordMapper reductionActivityBalanceRecordMapper;

    @Autowired
    private SettleInfoPushService settleInfoPushService;

    @Value("${qujia.payBaseUrl}")
    private String payBaseUrl;


//    String public_certPath="C:\\Users\\zcs\\Desktop\\商户密钥\\xdzf_cfca_prd.cer"; //现代支付公钥地址


    String public_certPath = "/home/jinkongzhengshu/xdzf_cfca_prd.cer"; //现代支付公钥地址

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RestTemplate restTemplate;

    //小票补打
    @GetMapping("/feiePush")
    public AjaxResult feiePush(PayOrder payOrder1) { //
        try {

            PayOrder payOrder = payOrderService.selectPayOrderForFeiEById(payOrder1.getOrderId());
            StationDeviceManage stationDeviceManage = new StationDeviceManage();
            stationDeviceManage.setStationId(payOrder.getStationId());
            stationDeviceManage.setDeviceType("3");
            List<StationDeviceManage> stationDeviceManages = stationDeviceManageService.selectStationDeviceManageList(stationDeviceManage);
            if (stationDeviceManages == null || stationDeviceManages.size() <= 0) {
                return AjaxResult.error("当前站点没有打印机");
            }

            StationDeviceManage stationDeviceManagerRes;

            try {
                //筛选绑定了用户的小票机
                List<StationDeviceManage> manageWithUser = new ArrayList<>();
                if (payOrder != null && payOrder.getOilPersonnelId() != null && !"".equals(payOrder.getOilPersonnelId())) {
                    manageWithUser = stationDeviceManages.stream().filter(device -> {
                        if (StringUtils.isNotBlank(device.getUserIds())) {
                            List<String> userIdsList = Arrays.asList(device.getUserIds().split(","));
                            return userIdsList.contains(payOrder.getOilPersonnelId());
                        }
                        return false;
                    }).collect(Collectors.toList());
                }
                stationDeviceManagerRes = CollectionUtils.isNotEmpty(manageWithUser) ? manageWithUser.get(0) : stationDeviceManages.get(0);
                log.info("筛选绑定用户的小票机信息：{}", stationDeviceManagerRes);
            } catch (Exception e) {
                stationDeviceManagerRes = stationDeviceManages.get(0);
                log.error(e.getMessage());
            }

            String audio = stationDeviceManagerRes.getAudio();
            log.info("自定义语音audio:{}", audio);

            log.info("最终小票机信息：{}", stationDeviceManagerRes);
            String deviceFactory = stationDeviceManagerRes.getDeviceFactory();
            PrintEnum printEnum = PrintEnum.getByCode(deviceFactory);

            ResultData resultData = restTemplate.getForObject(payBaseUrl + "/receiptSection/getOrderReceiptString?orderNo={1}&deviceFactory={2}&printType={3}&his={4}", ResultData.class,
                    payOrder.getOrderNo(), deviceFactory, stationDeviceManagerRes.getPrintType(), false);
            if (resultData.getCode() != 0) {
                throw new CustomException(resultData.getMsg());
            }
            String receiptStr = (String) resultData.getData();

            Oil oil = oilMapper.selectOilByName(payOrder.getOilName());

            String printRes = "";
            AjaxResult ajaxResult = AjaxResult.success();
            switch (printEnum) {
                case YILIANYUNK4:
                    if (oil != null) {
                        payOrder.setOilName(oil.getOilId().toString());
                    }
                    ajaxResult = YiLianYunPrinterUtil.print(receiptStr, stationDeviceManagerRes, payOrder);
                    break;

                case YILIANYUN:
                    if (oil != null) {
                        payOrder.setOilName(oil.getOilId().toString());
                    }
                    ajaxResult = YiLianYunPrinterUtil.print(receiptStr, stationDeviceManagerRes, payOrder);
                    break;
                case FEIE:
                    String result = FeiEPrinterUtil.printReceipt(stationDeviceManages.get(0).getDeviceNo(), receiptStr);
                    org.json.JSONObject resJson = new org.json.JSONObject(result);
                    if ("ok".equals(resJson.get("msg"))) {
                        printRes = "补打小票成功";
                        ajaxResult = AjaxResult.success(printRes);
                    } else {
                        printRes = "补打小票失败";
                        ajaxResult = AjaxResult.error(printRes);
                    }

                    break;
                default:
                    log.info("没有配置小票机，打印失败");
                    break;
            }

            int i = (int) ajaxResult.get("code");
            if (i == 200) {
                payOrderService.updatePayOrderPrintStatus(payOrder.getOrderNo());
            }

            return ajaxResult;
//
//            FeiEPrinterUtil.printReceipt(stationDeviceManages.get(0).getDeviceNo(), content.toString());
//            return AjaxResult.success("打印成功");
        } catch (Exception e) {
            logger.error(">pushConsumeToUser", e);
            return AjaxResult.error(e.getMessage());
        }

    }

    private String getElectronicCardAmt(PayOrder payOrder) {
//        Enterprise enterprise = enterpriseService.selectEnterpriseById(payOrder.getEnterpriseId());
//        String cardUseRangeFlag = enterprise.getCardUseRangeFlag();
//
//        SysAppUserInfoUser sysAppUserInfoUser = appUserInfoUserService.selectAppUserInfoById(Long.valueOf(payOrder.getConsumerId()));
//        log.info("用户信息{}",sysAppUserInfoUser.toString());
//        CustomerElectronicCard customerElectronicCard = new CustomerElectronicCard();
//        customerElectronicCard.setCustomerNo(sysAppUserInfoUser.getMemberCode());
//
//        if("1".equals(cardUseRangeFlag)){
//            customerElectronicCard.setStationId(payOrder.getEnterpriseId());
//        }else if("2".equals(cardUseRangeFlag)){
//            customerElectronicCard.setStationId2(payOrder.getStationId());
//        }
//
//        String cardOilType =  "汽油".equals(payOrder.getOrderType()) ? "1" : "2";
//        customerElectronicCard.setCardOilsType(cardOilType);
//        log.info("customerElectronicCard:{}",customerElectronicCard);
//        CustomerElectronicCard electronicCardInfo =  customerElectronicCardService.getElectronicCardInfo(customerElectronicCard);
//        log.info("电子卡信息：{}",electronicCardInfo.toString());
//        return Objects.nonNull(electronicCardInfo) ? electronicCardInfo.getAmt().toString() : "0";
        CustomerCardUseRecord customerCardUseRecord = customerCardUseRecordService.selectCustomerCardUseRecordByOrderNo(payOrder.getOrderNo());
        return Objects.nonNull(customerCardUseRecord) ? customerCardUseRecord.getBalance().toString() : "0";


    }


    /**
     * 查询订单支付列表
     * 这个方法在前端展示为退款列表
     */
    @GetMapping("/list")
    public TableDataInfo list(PayOrder payOrder) {
       /* List<String> list = deptService.levelDeptList(payOrder.getLevelId());
        if(list!=null && list.size()>0){
            payOrder.setStationIdList(list);
            payOrder.setStationId(null);
        }*/
//        说明：产品需求，繁星订单应该被过滤掉，以这个来做sql判断条件
        payOrder.setStarOrderSource("222");
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            if(CollectionUtil.isEmpty(stations)){
                return getDataTable(new ArrayList<>());
            }
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }

        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder=   payOrderService.timeSetting(payOrder,current.getUser().getStationId());
            payOrder.setStationId(current.getUser().getStationId());
            if (StaffUtil.isStaff(current.getUser())) {
                payOrder.setOilPersonnelId(String.valueOf(current.getUser().getUserId()));
            } else {
                Station station = stationService.selectStationById(current.getUser().getStationId());
                String showPayWayIds = station.getShowPayWayIds();
                if (showPayWayIds != null) {
                    String[] idArray = showPayWayIds.split(","); // 拆分成字符串数组
                    List<Long> idList = new ArrayList<>();
                    for (int i = 0; i < idArray.length; i++) {
                        String id = idArray[i].trim();
                        if (!id.isEmpty()) {
                            idList.add(Long.parseLong(id));
                        }
                    }
                    payOrder.setPayWayIdList(idList);
                }
            }
        } else if(SecurityUtils.isPartner()){
            EnterpriseAndStationVo itemIds = stationService.getItemIds(current.getUser());
            if(itemIds == null){
                throw new CustomException(UserConstants.NO_ENTERPRISE);
            }
            List<Long> stationIds = itemIds.getStationIds();
            payOrder.setStationIdList(itemIds.getStationIdsStr());
            List<Station> stations = stationService.list(new QueryWrapper<Station>().in("station_id", stationIds));
            for (Station station : stations) {
                String showPayWayIds = station.getShowPayWayIds();
                if (showPayWayIds != null) {
                    String[] idArray = showPayWayIds.split(","); // 拆分成字符串数组
                    List<Long> idList = new ArrayList<>();
                    for (int i = 0; i < idArray.length; i++) {
                        String id = idArray[i].trim();
                        if (!id.isEmpty()) {
                            idList.add(Long.parseLong(id));
                        }
                    }
                    payOrder.setPayWayIdList(idList);
                }
            }
        }
        startPage();
        //payOrder.setStatus("1");
        List<PayOrder> payOrderList = new ArrayList<>();
        if (payOrder.getPayType() != null && payOrder.getPayType().equals("cdk")) {
            payOrder.setCdkId(payOrder.getConsumerId());
            payOrder.setConsumerId(null);
            if (payOrder.getCdkType() != null && payOrder.getCdkType().equals("fleet_card")) {
                //车队主卡消费记录如果是共享模式，要包含子卡的消费记录
                payOrderList = payOrderService.selectCdkPayOrderList(payOrder);
                //历史数据
                //payOrderList.addAll(payOrderService.selectCdkPayHisOrderList(payOrder));
            } else {
                payOrderList = payOrderService.selectPayOrderAndHisPayOrderList(payOrder);
            }
        } else {
            payOrderList = payOrderService.selectPayOrderList(payOrder);
        }

        return getDataTable(payOrderList);
    }


    /**
     * 查询按照油品汇总的订单
     */
    @GetMapping("/selectOilPayOrderSum")
    public TableDataInfo selectOilPayOrderSum(PayOrder oilPayOrderSum) {
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            if(CollectionUtil.isEmpty(stations)){
                return getDataTable(new ArrayList<>());
            }
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                oilPayOrderSum.setStationIdList(list);
            }

        } else if ("2".equals(current.getUser().getUserLevel())) {
            oilPayOrderSum.setStationId(current.getUser().getStationId());
        } else if (SecurityUtils.isPartner()) {
            EnterpriseAndStationVo itemIds = stationService.getItemIds(current.getUser());
            if(itemIds == null){
                throw new CustomException(UserConstants.NO_ENTERPRISE);
            }
            oilPayOrderSum.setEnterpriseIdListForAuthor(itemIds.getEnterpriseIds());
            oilPayOrderSum.setStationIdList(itemIds.getStationIdsStr());
        } else if (UserConstants.LEVEL_FIVE.equals(current.getUser().getUserLevel()) || UserConstants.LEVEL_SIX.equals(current.getUser().getUserLevel())) {
            //区域经理和业务员
            List<StationByEnterpriseVo> stationByEnterprise = null;
            if (null != oilPayOrderSum.getStationId()) { // 根据油站筛选

            } else if (null != oilPayOrderSum.getEnterpriseId()) {//根据油企筛选
                stationByEnterprise = stationService.getStationByEnterprise(oilPayOrderSum.getEnterpriseId());
            } else {// 会根据当前账号去获取所有油站
                stationByEnterprise = stationService.getStationByEnterprise(null);
            }
            if (null != stationByEnterprise) {
                List<String> stationIds = stationByEnterprise.stream().map(x -> x.getStationId() + "").collect(Collectors.toList());
                oilPayOrderSum.setStationIdList(stationIds);
            }
        }
        startPage();
        List<OilPayOrderSum> payOrderList = payOrderService.selectOilPayOrderSum(oilPayOrderSum);
        return getDataTable(payOrderSumList(payOrderList));
    }

    private List<OilPayOrderSum> payOrderSumList(List<OilPayOrderSum> payOrderList) {
        OilPayOrderSum oilPayOrderSum = new OilPayOrderSum();
        oilPayOrderSum.setOilName("合计");
        payOrderList.stream().forEach(payOrderSum -> {
            oilPayOrderSum.setOrderLiters((Objects.nonNull(oilPayOrderSum.getOrderLiters()) ? oilPayOrderSum.getOrderLiters() : BigDecimal.ZERO).add(
                    (Objects.nonNull(payOrderSum.getOrderLiters()) ? payOrderSum.getOrderLiters() : BigDecimal.ZERO)));
            oilPayOrderSum.setAmt((Objects.nonNull(oilPayOrderSum.getAmt()) ? oilPayOrderSum.getAmt() : BigDecimal.ZERO).add(
                    (Objects.nonNull(payOrderSum.getAmt()) ? payOrderSum.getAmt() : BigDecimal.ZERO)));
            oilPayOrderSum.setReceivableAmt((Objects.nonNull(oilPayOrderSum.getReceivableAmt()) ? oilPayOrderSum.getReceivableAmt() : BigDecimal.ZERO).add(
                    (Objects.nonNull(payOrderSum.getReceivableAmt()) ? payOrderSum.getReceivableAmt() : BigDecimal.ZERO)));
            oilPayOrderSum.setDiscountAmt((Objects.nonNull(oilPayOrderSum.getDiscountAmt()) ? oilPayOrderSum.getDiscountAmt() : BigDecimal.ZERO).add(
                    (Objects.nonNull(payOrderSum.getDiscountAmt()) ? payOrderSum.getDiscountAmt() : BigDecimal.ZERO)));
            oilPayOrderSum.setDiscountCouponAmt((Objects.nonNull(oilPayOrderSum.getDiscountCouponAmt()) ? oilPayOrderSum.getDiscountCouponAmt() : BigDecimal.ZERO).add(
                    (Objects.nonNull(payOrderSum.getDiscountCouponAmt()) ? payOrderSum.getDiscountCouponAmt() : BigDecimal.ZERO)));
            oilPayOrderSum.setSumDiscount((Objects.nonNull(oilPayOrderSum.getSumDiscount()) ? oilPayOrderSum.getSumDiscount() : BigDecimal.ZERO).add(
                    (Objects.nonNull(payOrderSum.getSumDiscount()) ? payOrderSum.getSumDiscount() : BigDecimal.ZERO)));
            oilPayOrderSum.setCountNum((Objects.nonNull(oilPayOrderSum.getCountNum()) ? oilPayOrderSum.getCountNum() : 0)
                    + (Objects.nonNull(payOrderSum.getCountNum()) ? payOrderSum.getCountNum() : 0));
        });

        payOrderList.add(oilPayOrderSum);
        return payOrderList;
    }

    /**
     * 查询按照油品汇总的订单
     */
    @GetMapping("/selectOilPayOrderSumExport")
    public AjaxResult selectOilPayOrderSumExport(PayOrder oilPayOrderSum) {
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            if(CollectionUtil.isEmpty(stations)){
                return AjaxResult.success("");
            }
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                oilPayOrderSum.setStationIdList(list);
            }

        } else if ("2".equals(current.getUser().getUserLevel())) {
            oilPayOrderSum.setStationId(current.getUser().getStationId());
        } else if ("7".equals(current.getUser().getUserLevel())) {
            List<Enterprise> enterpriseList =
                    enterpriseService.list(new QueryWrapper<Enterprise>().in("author_id", current.getUser().getUserId()));
            if (enterpriseList != null && enterpriseList.size() > 0) {
                List<Long> enterpriseIds = enterpriseList.stream().map(Enterprise::getEnterpriseId).collect(Collectors.toList());
                oilPayOrderSum.setEnterpriseIdListForAuthor(enterpriseIds);
                for (Long enterId : enterpriseIds) {
                    Station station = new Station();
                    station.setEnterpriseId(enterId);
                    List<Station> stations = stationService.selectStationList(station);
                    for (Station ss : stations) {
                        list.add(ss.getStationId() + "");
                    }
                }
                if (CollectionUtils.isNotEmpty(list)) {
                    oilPayOrderSum.setStationIdList(list);
                }
            } else {
                throw new CustomException(UserConstants.NO_ENTERPRISE);
            }
        } else if (UserConstants.LEVEL_FIVE.equals(current.getUser().getUserLevel()) || UserConstants.LEVEL_SIX.equals(current.getUser().getUserLevel())) {
            //区域经理和业务员
            List<StationByEnterpriseVo> stationByEnterprise = null;
            if (null != oilPayOrderSum.getStationId()) { // 根据油站筛选

            } else if (null != oilPayOrderSum.getEnterpriseId()) {//根据油企筛选
                stationByEnterprise = stationService.getStationByEnterprise(oilPayOrderSum.getEnterpriseId());
            } else {// 会根据当前账号去获取所有油站
                stationByEnterprise = stationService.getStationByEnterprise(null);
            }
            if (null != stationByEnterprise) {
                List<String> stationIds = stationByEnterprise.stream().map(x -> x.getStationId() + "").collect(Collectors.toList());
                oilPayOrderSum.setStationIdList(stationIds);
            }
        }
        List<OilPayOrderSum> payOrderList = payOrderService.selectOilPayOrderSum(oilPayOrderSum);
        payOrderList.add(payOrderService.selectOilPayOrderAllSum(oilPayOrderSum));
        return AjaxResult.success(exportSum(oilPayOrderSum, payOrderList, current));

    }

    // 导出带标题的excel表
    private String exportSum(PayOrder oilPayOrderSum, List<OilPayOrderSum> payOrderList, LoginUser current) {
        OutputStream out = null;
        String stationName = "全部油站";
        Long enterpriseId = current.getUser().getEnterpriseId();
        if (Objects.nonNull(oilPayOrderSum) && Objects.nonNull(oilPayOrderSum.getStationId())) {
            Station station = stationService.selectStationById(oilPayOrderSum.getStationId());
            if (Objects.nonNull(station) && StringUtils.isNotEmpty(station.getStationName())) {
                stationName = station.getStationName();
            }
        }
        Map<String, Object> map = getTitle(oilPayOrderSum);
        String title = map.get("title").toString();
        ExportParams params = new ExportParams(stationName, title, "StatisticsPayOrder");
        Workbook workbook = ExcelExportUtil.exportExcel(params, OilPayOrderSum.class, payOrderList);
        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        String filename = "";
        try {

            filename = encodingFilename(getFileName(oilPayOrderSum, enterpriseId, map));
            out = new FileOutputStream(getAbsoluteFile(filename));
            workbook.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return filename;
    }

    private Map<String, Object> getTitle(PayOrder payOrder) {
        Map<String, Object> map = new HashMap<>();
        String startTime = DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", DateUtils.getTodayStartTime());
        String endTime = DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", new Date());
        if (Objects.isNull(payOrder)) {
            map.put("title", "汇总时间：---- ~ " + startTime);
            return map;
        }
        // 选择今日订单
        if (StringUtils.isNotBlank(payOrder.getHistoryFlag()) && "1".equals(payOrder.getHistoryFlag())) {
            // 未选择支付时间
            if (StringUtils.isBlank(payOrder.getBeginTime()) || StringUtils.isBlank(payOrder.getEndTime())) {
                map.put("title", "汇总时间：" + startTime + " ~ " + endTime);
                map.put("startTime", startTime);
                map.put("endTime", endTime);
                return map;
            }
            // 选择支付时间
            if (startTime.compareTo(payOrder.getBeginTime()) > 0) {
                map.put("title", "汇总时间：" + startTime + " ~ " + payOrder.getEndTime());
                map.put("startTime", startTime);
                map.put("endTime", payOrder.getEndTime());
                return map;
            } else {
                // 汇总时间：2023-09-12 00:00:00 ~ 2023-09-17 00:00:00
                map.put("title", "汇总时间：" + payOrder.getBeginTime() + " ~ " + payOrder.getEndTime());
                map.put("startTime", payOrder.getBeginTime());
                map.put("endTime", payOrder.getEndTime());
                return map;
            }

        } else if (StringUtils.isNotBlank(payOrder.getBeginTime()) && StringUtils.isNotBlank(payOrder.getEndTime())) {
            // 选择全部订单+支付时间
            map.put("title", "汇总时间：" + payOrder.getBeginTime() + " ~ " + payOrder.getEndTime());
            map.put("startTime", payOrder.getBeginTime());
            map.put("endTime", payOrder.getEndTime());
            return map;
        }

        map.put("title", "汇总时间：---- ~ " + endTime);
        return map;
    }

    private String getFileName(PayOrder payOrder, Long enterpriseId, Map<String, Object> map) {
        if (Objects.isNull(payOrder)) {
            return "StatisticsPayOrder";
        }

        if (Objects.nonNull(payOrder.getStationId())) {
            // 油站
            Station station = stationService.selectStationById(payOrder.getStationId());
            if (Objects.nonNull(station) && StringUtils.isNotEmpty(station.getStationName())) {
                String stationName = station.getStationName();
                if (Objects.nonNull(map.get("startTime")) && Objects.nonNull(map.get("endTime"))) {
                    return stationName + "汇总" + getDateSign(map.get("startTime").toString()) + "至" + getDateSign(map.get("endTime").toString());
                }
                return stationName + "汇总";
            }

        } else if (Objects.nonNull(enterpriseId)) {
            // 油企
            Enterprise enterprise = enterpriseService.selectEnterpriseById(enterpriseId);
            if (Objects.nonNull(enterprise) && StringUtils.isNotEmpty(enterprise.getEnterpriseName())) {
                String enterpriseName = enterprise.getEnterpriseName();
                if (Objects.nonNull(map.get("startTime")) && Objects.nonNull(map.get("endTime"))) {
                    return enterpriseName + "汇总" + getDateSign(map.get("startTime").toString()) + "至" + getDateSign(map.get("endTime").toString());
                }
                return enterpriseName + "汇总";
            }
        }

        // admin
        return "StatisticsPayOrder";
    }

    // 将 2023-09-12 00:00:00  转换成 2023年09月12日00时00分00秒
    private String getDateSign(String time) {
        Date date = DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", time);
        return DateUtils.parseDateToStr("yyyy年MM月dd日HH时mm分ss秒", date);
    }

    /**
     * 查询订单的统计量
     */
    @GetMapping("/selectPayOrderSum")
    public AjaxResult selectPayOrderSum(PayOrder payOrder) {
       /* List<String> list = deptService.levelDeptList(payOrder.getLevelId());
        if(list!=null && list.size()>0){
            payOrder.setStationIdList(list);
            payOrder.setStationId(null);
        }*/
        if (payOrder.getPartner() != null && !payOrder.getPartner().isEmpty()) {
            SysUser byId = sysUserService.getById(Long.valueOf(payOrder.getPartner()));
            EnterpriseAndStationVo itemIds = stationService.getItemIds(byId);
            if (itemIds != null && itemIds.getEnterpriseIds() != null &&itemIds.getEnterpriseIds().size()>0) {
                payOrder.setEnterpriseIdListForAuthor(itemIds.getEnterpriseIds());

            }else if(payOrder.getPartner().equals("1")){ } else {
                PayOrder reorder = new PayOrder();
                return AjaxResult.success(reorder);
            }
        }
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            if(CollectionUtil.isEmpty(stations)){
                return AjaxResult.success(new PayOrder());
            }
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }

        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else {
        }
        PayOrder sumPayOrder = payOrderService.selectSumPayOrder(payOrder);
        return AjaxResult.success(sumPayOrder);
    }


    @GetMapping("/updatePayOrderAmt")
    @ApiOperation("修改一段时间内的订单的金额")
    public AjaxResult updatePayOrderAmt(@RequestParam("startTime") String startTime,
                                        @RequestParam("endTime") String endTime,
                                        @RequestParam("discountAmount") BigDecimal discountAmount) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime startDateTime = LocalDateTime.parse(startTime.replace("+", " "), formatter);
        LocalDateTime endDateTime = LocalDateTime.parse(endTime.replace("+", " "), formatter);

        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        Map<String, Object> params = new HashMap<>();
        params.put("startTime", startDateTime);
        params.put("endTime", endDateTime);
        params.put("discountAmount", discountAmount);

        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            if(CollectionUtil.isEmpty(stations)){
                return AjaxResult.error("未查询到油站");
            }
            List<Long> stationIds = new ArrayList<>();
            for (Station ss : stations) {
                stationIds.add(ss.getStationId());
            }
            if (!stationIds.isEmpty()) {
                params.put("stationIdList", stationIds);
            }
        } else if ("2".equals(current.getUser().getUserLevel())) {
            params.put("stationId", current.getUser().getStationId());
        }

        // 创建订单优惠金额修改日志对象
        OrderAmountModificationLog modificationLog = new OrderAmountModificationLog();
        modificationLog.setUserId(current.getUser().getUserId());

        // 设置用户名，进行非空判断
        String username = current.getUser().getUserName();
        if (username != null && !username.isEmpty()) {
            modificationLog.setUsername(username);
        }

        // 设置手机号，进行非空判断
        String phoneNumber = current.getUser().getPhonenumber();
        if (phoneNumber != null && !phoneNumber.isEmpty()) {
            modificationLog.setPhoneNumber(phoneNumber);
        }

        // 设置 IP 地址，进行非空判断
        String ipAddress = current.getIpaddr();
        if (ipAddress != null && !ipAddress.isEmpty()) {
            modificationLog.setIpAddress(ipAddress);
        }

        modificationLog.setModificationTime(new Date());
        Date startDate = Date.from(startDateTime.atZone(ZoneId.systemDefault()).toInstant());
        Date endDate = Date.from(endDateTime.atZone(ZoneId.systemDefault()).toInstant());

        modificationLog.setStartTime(startDate);
        modificationLog.setEndTime(endDate);
        modificationLog.setDiscountAmount(discountAmount);

        try {
            payOrderService.updatePayOrderAmt(params);
            payOrderHistoryService.updatePayOrderAmt(params);
            // 添加订单优惠金额修改日志
            payOrderService.addOrderAmountModificationLog(modificationLog);

            return AjaxResult.success("订单金额修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            // 进行适当的异常处理
            return AjaxResult.error("订单金额修改失败");
        }
    }


    /**
     * 批量删除订单
     *
     * @return
     */
    @DeleteMapping("/deletePay")
    @ApiOperation("批量删除")
    public AjaxResult deletePay(@RequestBody List<Long> list) {
        if (CollectionUtils.isEmpty(list)) {
            return AjaxResult.error();
        }
        List<Long> newOrderIdList = new ArrayList<>();
        List<Long> historyOrderIdList = new ArrayList<>();
        payOrderAllService.deletePay(list);
        for (Long orderId : list) {
            PayOrder payOrder = payOrderService.selectPayOrderById(orderId);
            if (Objects.nonNull(payOrder)) {
                deletePhysicalCardOrder(payOrder);
                newOrderIdList.add(orderId);
            } else {
                deleteHistoryPhysicalCardOrder(orderId);
                historyOrderIdList.add(orderId);
            }
        }
        int i = 0;
        if (CollectionUtils.isNotEmpty(newOrderIdList)) {
            i = payOrderService.deletePay(newOrderIdList);
        }
        int j = 0;
        if (CollectionUtils.isNotEmpty(historyOrderIdList)) {
            j = payOrderHistoryService.deletePay(historyOrderIdList);
        }
        if ((i + j) <= 0) {
            return AjaxResult.error();
        }
        return AjaxResult.success();
    }

    /**
     * 批量删除订单
     *
     * @return
     */
    @DeleteMapping("/deleteAllPay")
    @ApiOperation("批量删除某商户号下所有订单")
    public AjaxResult deleteAllPay(@RequestBody PayOrder payOrder) {
        if (payOrder == null) {
            return AjaxResult.error();
        }

        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            if(CollectionUtil.isEmpty(stations)){
                return AjaxResult.error("未查询到油站");
            }
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }
        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else {

        }
        if (payOrder.getStationId() == null) {
            return AjaxResult.error("油站不能为空");
        }
        List<Long> newOrderIdList = new ArrayList<>();
        List<Long> historyOrderIdList = new ArrayList<>();
        payOrderAllService.deleteAllPay(payOrder);
        int i = 0;
        i = payOrderAllService.deleteAllPay2(payOrder);
        int j = 0;
        j = payOrderAllService.deleteAllPay3(payOrder);

        if ((i + j) <= 0) {
            return AjaxResult.error();
        }
        return AjaxResult.success();
    }


    // 今日订单表 同步删除实体卡消费订单
    private void deletePhysicalCardOrder(PayOrder payOrder) {
        if (Objects.isNull(payOrder) || StringUtils.isEmpty(payOrder.getPayType())) {
            return;
        }
        if (PayTypeEnum.dkq.getType().equals(payOrder.getPayType())) {
            PhysicalCardBalance physicalCardBalance = new PhysicalCardBalance();
            physicalCardBalance.setBalanceNo(payOrder.getOrderNo());
            physicalCardBalance.setIsDeleted("1");
            physicalCardBalanceService.updatePhysicalCardBalance(physicalCardBalance);
        }
    }

    // 历史订单表 同步删除实体卡消费订单
    private void deleteHistoryPhysicalCardOrder(Long orderId) {
        PayOrder payOrder = payOrderHistoryService.selectPayOrderById(orderId);
        if (Objects.nonNull(payOrder)) {
            deletePhysicalCardOrder(payOrder);
        }
    }
    public String lastTimeByUserIdBGApi(Long userId) throws InterruptedException {

        SysUser uuser =   sysUserService.getById(userId);
        List<Long> roleIds = classSettlementService.selectSysUserByCreateUser(userId);
        List<SysRole> roles = new ArrayList<>();
        for(Long roleId:roleIds){
            SysRole a = new SysRole();
            a.setRoleId(roleId);
            roles.add(a);
        }
        uuser.setRoles(roles);
        Map<String, Object> params = new HashMap<String, Object>();
        String startTime = null;
        String sign = sysUserService.getEmployeeSign(uuser.getUserId());
        // 员工权限
        if(uuser!=null && sign.equals("1")){

            Station station =  stationService.selectStationById(uuser.getStationId());
            params.put("stationId", station.getStationId());
            params.put("oilPersonnelId", "0");
            if(station.getOpenStaffClass() == 1) {
                params.put("oilPersonnelId",userId);
            }

            Map<String, Object> endTimeMap = classSettlementService.queryLastEndTimeStaff(params);
            if (endTimeMap == null ){
                endTimeMap = classSettlementService.queryLastEndTime(params);
            }
            if (endTimeMap != null && endTimeMap.containsKey("classStartTime") && endTimeMap.get("classStartTime") != null) {
                    startTime = (DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", (Date) endTimeMap.get("classStartTime")));
            }else{
                startTime = "2024-01-01 09:00:00";
            }

        }else{

            params.put("stationId", uuser.getStationId());

            Map<String, Object> endTimeMap = classSettlementService.queryLastEndTime(params);
            if (endTimeMap != null && endTimeMap.containsKey("classStartTime") && endTimeMap.get("classStartTime") != null) {
                startTime = (DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", (Date) endTimeMap.get("classStartTime")));
            }else{
                startTime = "2024-01-01 09:00:00";
            }

        }
        return  startTime;
    }

    @ApiOperation(value = "获取pos机订单默认时段", httpMethod = "GET", notes = "获取pos机订单默认时段")
    @GetMapping( value = "/selectPosDefaultQueryPeriod")
    public  ResultData selectPosDefaultQueryPeriod(@ApiParam(value = "油站id") Long stationId, Long userId) {
        Gson gson = new Gson();
        if(stationId == null){
            return  ResultData.error("stationId不能为空");
        }
        SysUser staffuser =  userService.getById(userId);
        // 角色为员工标识
//        boolean staff = StaffUtil.isStaff(staffuser);

        Station station = stationService.selectStationById(stationId);
        String posDefaultQueryPeriod = station.getDefaultTimePeriodOrder();
        Map<String,String> result=new HashMap<>();
        SimpleDateFormat dateFormat1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat dateFormat2=new SimpleDateFormat("yyyy-MM-dd");
        String startTime = dateFormat2.format(new Date())+" 00:00:00";
        String endTime = dateFormat1.format(new Date());
//        if(staff){
//            result.put("startTime",startTime);
//            result.put("endTime",endTime);
//            return ResultData.success(result);
//        }
        try{
            if(StringUtils.isNotEmpty(station.getDefaultTimePeriodOrder())){
                if(posDefaultQueryPeriod.equals(Station.POSDEFAULTQUERYPERIOD_LAST_HALF_HOUR)){
                    if(dateFormat1.parse(dateFormat2.format(new Date())+" 00:30:00").before(new Date())){
                        Calendar calendar = Calendar.getInstance();
                        calendar.add(Calendar.MINUTE, -30);
                        startTime = dateFormat1.format(calendar.getTime());
                    }
                }
                if(posDefaultQueryPeriod.equals(Station.POSDEFAULTQUERYPERIOD_ALL)){
                    // 开始时间和结束时间为空的逻辑
                    LocalDate today = LocalDate.now(); // 当前日期
                    LocalDate sevenDaysAgo = today.minusDays(7); // 当前日期往前7天的日期

                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); // 定义日期时间格式化模式

                    LocalDateTime beginTime2 = LocalDateTime.of(sevenDaysAgo, LocalTime.MIN); // 开始时间为当天的最早时间（00:00:00）
                    LocalDateTime endTime2 = LocalDateTime.of(today, LocalTime.MAX); // 结束时间为当天的最晚时间（23:59:59）

                    String beginTimeStr = beginTime2.format(formatter); // 格式化开始时间为字符串
                    String endTimeStr = endTime2.format(formatter); // 格式化结束时间为字符串

// 将开始时间和结束时间的字符串赋值给相应的变量
                    startTime = beginTimeStr;
                    endTime=endTimeStr;
                }
                if(posDefaultQueryPeriod.equals(Station.POSDEFAULTQUERYPERIOD_LAST_HOUR)){
                    if(dateFormat1.parse(dateFormat2.format(new Date())+" 01:00:00").before(new Date())){
                        Calendar calendar = Calendar.getInstance();
                        calendar.add(Calendar.HOUR, -1);
                        startTime = dateFormat1.format(calendar.getTime());
                    }
                }
                if(posDefaultQueryPeriod.equals(Station.POSDEFAULTQUERYPERIOD_LAST_SHIFT_TIME)){
                    if(userId == null){

                        return  ResultData.error("没有userId");
                    }

                    String lastTime = this.lastTimeByUserIdBGApi(userId);

                    if(lastTime == null){
                        return  ResultData.error("查无数据");
                    }
                    startTime = lastTime;
                }
                if(posDefaultQueryPeriod.equals(Station.POSDEFAULTQUERYPERIOD_LAST_SHIFT_TIME_END)){
                    Map<String, Object> params = new HashMap<String, Object>();
                    params.put("stationId", stationId);

                    Map<String, Object>     endTimeMap = classSettlementService.queryLastEndTime(params);
                    if (endTimeMap != null && !endTimeMap.isEmpty()
                            && Objects.nonNull(endTimeMap.get("classEndTime"))) {
                        startTime = (DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", (Date) endTimeMap.get("classEndTime")));

                    }
                }
            }
        }catch (Exception e){
            return  ResultData.error(e.getMessage());
        }
        result.put("startTime",startTime);
        result.put("endTime",endTime);
        return ResultData.success(result);
    }
    @ApiOperation(value = "获取pos机班结默认时段", httpMethod = "GET", notes = "获取pos机订单默认时段")
    @GetMapping( value = "/selectPosClassDefaultQueryPeriod")
    public ResultData selectPosClassDefaultQueryPeriod(@ApiParam(value = "油站id") Long stationId, Long userId) {
        Gson gson = new Gson();
        if(stationId ==null){
            return ResultData.error("stationId不能为空");
        }
        Station station = stationService.selectStationById(stationId);
        String posDefaultQueryPeriod = station.getDefaultTimePeriodClass();
        Map<String,String> result=new HashMap<>();
        SimpleDateFormat dateFormat1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat dateFormat2=new SimpleDateFormat("yyyy-MM-dd");
        String startTime = dateFormat2.format(new Date())+" 00:00:00";
        String endTime = dateFormat1.format(new Date());

        try{
            if(StringUtils.isNotEmpty(station.getDefaultTimePeriodClass())){
                if(posDefaultQueryPeriod.equals(Station.POSDEFAULTQUERYPERIOD_ALL)){
                    // 开始时间和结束时间为空的逻辑
                    LocalDate today = LocalDate.now(); // 当前日期
                    LocalDate sevenDaysAgo = today.minusDays(7); // 当前日期往前7天的日期

                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); // 定义日期时间格式化模式

                    LocalDateTime beginTime2 = LocalDateTime.of(sevenDaysAgo, LocalTime.MIN); // 开始时间为当天的最早时间（00:00:00）
                    LocalDateTime endTime2 = LocalDateTime.of(today, LocalTime.MAX); // 结束时间为当天的最晚时间（23:59:59）

                    String beginTimeStr = beginTime2.format(formatter); // 格式化开始时间为字符串
                    String endTimeStr = endTime2.format(formatter); // 格式化结束时间为字符串

// 将开始时间和结束时间的字符串赋值给相应的变量
                    startTime = beginTimeStr;
                    endTime=endTimeStr;
                }
                if(posDefaultQueryPeriod.equals(Station.POSDEFAULTQUERYPERIOD_LAST_HALF_HOUR)){
                    if(dateFormat1.parse(dateFormat2.format(new Date())+" 00:30:00").before(new Date())){
                        Calendar calendar = Calendar.getInstance();
                        calendar.add(Calendar.MINUTE, -30);
                        startTime = dateFormat1.format(calendar.getTime());
                    }
                }
                if(posDefaultQueryPeriod.equals(Station.POSDEFAULTQUERYPERIOD_LAST_HOUR)){
                    if(dateFormat1.parse(dateFormat2.format(new Date())+" 01:00:00").before(new Date())){
                        Calendar calendar = Calendar.getInstance();
                        calendar.add(Calendar.HOUR, -1);
                        startTime = dateFormat1.format(calendar.getTime());
                    }
                }
                if(posDefaultQueryPeriod.equals(Station.POSDEFAULTQUERYPERIOD_WEEK)){
                    Calendar cal = Calendar.getInstance();
                    cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); // 设置为本周的星期一
                    cal.set(Calendar.HOUR_OF_DAY, 0);
                    cal.set(Calendar.MINUTE, 0);
                    cal.set(Calendar.SECOND, 0);
                    cal.set(Calendar.MILLISECOND, 0);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    startTime = sdf.format(cal.getTime());
                }
                if(posDefaultQueryPeriod.equals(Station.POSDEFAULTQUERYPERIOD_MONTH)){
                    Calendar cal = Calendar.getInstance();
                    cal.set(Calendar.DAY_OF_MONTH, 1);
                    cal.set(Calendar.HOUR_OF_DAY, 0);
                    cal.set(Calendar.MINUTE, 0);
                    cal.set(Calendar.SECOND, 0);
                    cal.set(Calendar.MILLISECOND, 0);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    startTime = sdf.format(cal.getTime());
                }
                if(posDefaultQueryPeriod.equals(Station.POSDEFAULTQUERYPERIOD_LAST_SHIFT_TIME)){
                    Map<String, Object> params = new HashMap<String, Object>();
                    params.put("stationId", stationId);

                    Map<String, Object>     endTimeMap = classSettlementService.queryLastEndTime(params);
                    if (endTimeMap != null && !endTimeMap.isEmpty()
                            && Objects.nonNull(endTimeMap.get("classEndTime"))) {
                        startTime = (DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", (Date) endTimeMap.get("classEndTime")));

                    }
                }
            }
        }catch (Exception e){
            return ResultData.error(e.getMessage());
        }
        result.put("startTime",startTime);
        result.put("endTime",endTime);
        return ResultData.success(result);
    }

    /**
     * 查询所有订单包括未支付的
     */
    @GetMapping("/allList")
    public TableDataInfo allList(PayOrder payOrder) {
       /* List<String> list = deptService.levelDeptList(payOrder.getLevelId());
        if(list!=null && list.size()>0){
            payOrder.setStationIdList(list);
            payOrder.setStationId(null);
        }*/

        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            if(CollectionUtil.isEmpty(stations)){
                return getDataTable(new ArrayList<>());
            }
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }

        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
            payOrder=   payOrderService.timeSetting(payOrder,current.getUser().getStationId());

            if (StaffUtil.isStaff(current.getUser())) {
                payOrder.setOilPersonnelId(String.valueOf(current.getUser().getUserId()));
            } else {
                Station station = stationService.selectStationById(current.getUser().getStationId());
                String showPayWayIds = station.getShowPayWayIds();
                if (showPayWayIds != null) {
                    String[] idArray = showPayWayIds.split(","); // 拆分成字符串数组
                    List<Long> idList = new ArrayList<>();
                    for (int i = 0; i < idArray.length; i++) {
                        String id = idArray[i].trim();
                        if (!id.isEmpty()) {
                            idList.add(Long.parseLong(id));
                        }
                    }
                    payOrder.setPayWayIdList(idList);
                }
            }
        } else  if (SecurityUtils.isPartner()) {
            EnterpriseAndStationVo itemIds = stationService.getItemIds(current.getUser());
            if (itemIds != null && itemIds.getEnterpriseIds().size()>0){

                payOrder.setEnterpriseIdListForAuthor(itemIds.getEnterpriseIds());
                payOrder.setIsDeleted(null);
            } else {
                throw new CustomException(UserConstants.NO_ENTERPRISE);
            }
        }

        if (payOrder.getPartner() != null && !payOrder.getPartner().isEmpty()) {
            SysUser byId = sysUserService.getById(Long.valueOf(payOrder.getPartner()));
            EnterpriseAndStationVo itemIds = stationService.getItemIds(byId);
            if (itemIds != null && itemIds.getEnterpriseIds() != null &&itemIds.getEnterpriseIds().size()>0) {
                payOrder.setEnterpriseIdListForAuthor(itemIds.getEnterpriseIds());

            }else if(payOrder.getPartner().equals("1")){ } else {
                List<String> alist = new ArrayList<>();
                return getDataTable(alist);
            }
        }
        assignPayOrder(payOrder, current.getUser());

        LocalDate today = LocalDate.now();
        LocalDate tomorrow = today.plusDays(1);

        LocalDateTime startTime = today.atStartOfDay();
        LocalDateTime endTime = tomorrow.atStartOfDay();

        String currentBeginTime = payOrder.getBeginTime();
        String currentEndTime = payOrder.getEndTime();

        if (currentBeginTime != null && !currentBeginTime.isEmpty() && currentEndTime != null && !currentEndTime.isEmpty()) {
            LocalDateTime parsedBeginTime = LocalDateTime.parse(currentBeginTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            LocalDateTime parsedEndTime = LocalDateTime.parse(currentEndTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

            if (startTime.compareTo(parsedBeginTime) > 0) {
                String formattedStartTime = startTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                payOrder.setBeginTime(formattedStartTime);
            }

            if (endTime.compareTo(parsedEndTime) < 0) {
                String formattedEndTime = endTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                payOrder.setEndTime(formattedEndTime);
            }
        } else {
            String formattedStartTime = startTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            payOrder.setBeginTime(formattedStartTime);
            String formattedEndTime = endTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            payOrder.setEndTime(formattedEndTime);
        }


        startPage();
//        List<PayOrder> payOrderList = payOrderService.selectAllPayOrderList(payOrder);
        //List<PayOrder> payOrderList = payOrderService.selectPayOrderList(payOrder);
        List<PayOrder> payOrderList = payOrderService.selectPayOrderAndWithdrawalAmountList(payOrder);
        //组装合伙人
//        List<Long> collect = payOrderList.stream().map(PayOrder::getStationId).collect(Collectors.toList());
//        SysUser sysUser = new SysUser();
//        List<String> collect2 = collect.stream().map(String::valueOf).collect(Collectors.toList());
//        sysUser.setStationIdList(collect2);
//        List<SysUser> sysUsers = sysUserService.selectUserList(sysUser);
//        Map<Long, List<SysUser>> collect3 = sysUsers.stream().collect(Collectors.groupingBy(SysUser::getStationId));
//        //Map<Long, String> collect1 = sysUsers.stream().collect(Collectors.toMap(SysUser::getStationId, SysUser::getCreateBy));
//        for (PayOrder order : payOrderList) {
//            order.setPartner(collect3.get(order.getStationId()).get(1).getCreateBy());
//        }
        return getDataTable(payOrderList);
    }


    /**
     * 查询所有订单包括未支付的
     */
    @GetMapping("/selectStatisticsPayOrderList")
    public TableDataInfo selectStatisticsPayOrderList(PayOrder payOrder) {
         /* List<String> list = deptService.levelDeptList(payOrder.getLevelId());
        if(list!=null && list.size()>0){
            payOrder.setStationIdList(list);
            payOrder.setStationId(null);
        }*/
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            if(CollectionUtil.isEmpty(stations)){
                return getDataTable(new ArrayList<>());
            }
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }

        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else if ("7".equals(current.getUser().getUserLevel())) {
            List<Enterprise> enterpriseList =
                    enterpriseService.list(new QueryWrapper<Enterprise>().in("author_id", current.getUser().getUserId()));
            if (enterpriseList != null && enterpriseList.size() > 0) {
                List<Long> enterpriseIds = enterpriseList.stream().map(Enterprise::getEnterpriseId).collect(Collectors.toList());
                List<Station> stationList =
                        stationService.list(new QueryWrapper<Station>().in("enterprise_id", enterpriseIds));
                for (Station ss : stationList) {
                    list.add(ss.getStationId() + "");
                }
                payOrder.setStationIdList(list);
            } else {
                throw new CustomException("未创建油企");
            }
        }
        startPage();
        List<StatisticsPayOrder> payOrderList = payOrderService.selectStatisticsPayOrderList(payOrder);
        return getDataTable(payOrderList);
    }

    /**
     * 查询所有订单包括未支付的
     */
    @GetMapping("/selectStatisticsPayOrderSum")
    public AjaxResult selectStatisticsPayOrderSum(PayOrder payOrder) {
       /* List<String> list = deptService.levelDeptList(payOrder.getLevelId());
        if(list!=null && list.size()>0){
            payOrder.setStationIdList(list);
            payOrder.setStationId(null);
        }*/
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            if(CollectionUtil.isEmpty(stations)){
                return AjaxResult.success(new StatisticsPayOrder());
            }
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }

        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else if ("7".equals(current.getUser().getUserLevel())) {
            List<Enterprise> enterpriseList =
                    enterpriseService.list(new QueryWrapper<Enterprise>().in("author_id", current.getUser().getUserId()));
            if (enterpriseList != null && enterpriseList.size() > 0) {
                List<Long> enterpriseIds = enterpriseList.stream().map(Enterprise::getEnterpriseId).collect(Collectors.toList());
                List<Station> stationList =
                        stationService.list(new QueryWrapper<Station>().in("enterprise_id", enterpriseIds));
                for (Station ss : stationList) {
                    list.add(ss.getStationId() + "");
                }
                payOrder.setStationIdList(list);
            } else {
                throw new CustomException("未创建油企");
            }
        }
        startPage();
        payOrder.setStatus("1");
        StatisticsPayOrder statisticsPayOrder = payOrderService.selectStatisticsPayOrderSum(payOrder);
        return AjaxResult.success(statisticsPayOrder);
    }

    @GetMapping("/selectStatisticsPayOrderListExport")
    public AjaxResult selectStatisticsPayOrderListExport(PayOrder payOrder) {
       /* List<String> list = deptService.levelDeptList(payOrder.getLevelId());
        if(list!=null && list.size()>0){
            payOrder.setStationIdList(list);
            payOrder.setStationId(null);
        }*/
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            if(CollectionUtil.isEmpty(stations)){
                return AjaxResult.error("未查询到油站");
            }
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }

        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else if ("7".equals(current.getUser().getUserLevel())) {
            List<Enterprise> enterpriseList =
                    enterpriseService.list(new QueryWrapper<Enterprise>().in("author_id", current.getUser().getUserId()));
            if (enterpriseList != null && enterpriseList.size() > 0) {
                List<Long> enterpriseIds = enterpriseList.stream().map(Enterprise::getEnterpriseId).collect(Collectors.toList());
                List<Station> stationList =
                        stationService.list(new QueryWrapper<Station>().in("enterprise_id", enterpriseIds));
                for (Station ss : stationList) {
                    list.add(ss.getStationId() + "");
                }
                payOrder.setStationIdList(list);
            } else {
                throw new CustomException("未创建油企");
            }
        }
        payOrder.setStatus("1");
        List<StatisticsPayOrder> payOrderList = payOrderService.selectStatisticsPayOrderList(payOrder);
        StatisticsPayOrder statisticsPayOrder = payOrderService.selectStatisticsPayOrderSum(payOrder);
        statisticsPayOrder.setEnterpriseName("合计");
        payOrderList.add(statisticsPayOrder);
        ExcelUtil<StatisticsPayOrder> util = new ExcelUtil<>(StatisticsPayOrder.class);
        return util.exportExcel(payOrderList, "StatisticsPayOrder");
    }


    /**
     * 关联用户查询订单支付列表
     */
    @GetMapping("/selectUserPayOrderList")
    public TableDataInfo selectUserPayOrderList(PayOrder payOrder) {
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            if(CollectionUtil.isEmpty(stations)){
                return getDataTable(new ArrayList<>());
            }
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }

        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else if ("7".equals(current.getUser().getUserLevel())) {
            List<Enterprise> enterpriseList =
                    enterpriseService.list(new QueryWrapper<Enterprise>().in("author_id", current.getUser().getUserId()));
            if (enterpriseList != null && enterpriseList.size() > 0) {
                List<Long> enterpriseIds = enterpriseList.stream().map(Enterprise::getEnterpriseId).collect(Collectors.toList());
                List<Station> stationList =
                        stationService.list(new QueryWrapper<Station>().in("enterprise_id", enterpriseIds));
                for (Station ss : stationList) {
                    list.add(ss.getStationId() + "");
                }
                payOrder.setStationIdList(list);
            } else {
                throw new CustomException("未创建油企");
            }
        }
        startPage();
        //payOrder.setStatus("1");
        List<PayOrder> payOrderList = payOrderService.selectUserPayOrderList(payOrder);
        return getDataTable(payOrderList);
    }

    /**
     * selectDivideAccountsList
     */
    @GetMapping("/selectDivideAccountsList")
    @ApiOperation("查询分账记录")
    public TableDataInfo selectDivideAccountsList(DivideAccounts divideAccounts) {
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            if(CollectionUtil.isEmpty(stations)){
                return getDataTable(new ArrayList<>());
            }
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                divideAccounts.setStationIdList(list);
            }

        } else if ("2".equals(current.getUser().getUserLevel())) {
            divideAccounts.setStationId(Integer.valueOf(current.getUser().getStationId().intValue()));
        } else if ("7".equals(current.getUser().getUserLevel())) {
            List<Enterprise> enterpriseList =
                    enterpriseService.list(new QueryWrapper<Enterprise>().in("author_id", current.getUser().getUserId()));
            if (enterpriseList != null && enterpriseList.size() > 0) {
                List<Long> enterpriseIds = enterpriseList.stream().map(Enterprise::getEnterpriseId).collect(Collectors.toList());
                List<Station> stationList =
                        stationService.list(new QueryWrapper<Station>().in("enterprise_id", enterpriseIds));
                for (Station ss : stationList) {
                    list.add(ss.getStationId() + "");
                }
                divideAccounts.setStationIdList(list);
            } else {
                throw new CustomException("未创建油企");
            }
        }
        startPage();
        //payOrder.setStatus("1");
        List<DivideAccounts> divideAccountsList = payOrderService.queryDivideAccountsList(divideAccounts);

        return getDataTable(divideAccountsList);
    }

    @GetMapping("/selectDivideSettingList")
    @ApiOperation("查询分账规则列表")
    public TableDataInfo selectDivideSettingList(DivideAccountsSettingDto divideAccountsSettingDto) {
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            if(CollectionUtil.isEmpty(stations)){
                return getDataTable(new ArrayList<>());
            }
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                divideAccountsSettingDto.setStationIdList(list);
            }

        } else if ("2".equals(current.getUser().getUserLevel())) {
            divideAccountsSettingDto.setStationId(current.getUser().getStationId());
        } else if ("7".equals(current.getUser().getUserLevel())) {
            List<Enterprise> enterpriseList =
                    enterpriseService.list(new QueryWrapper<Enterprise>().in("author_id", current.getUser().getUserId()));
            if (enterpriseList != null && enterpriseList.size() > 0) {
                List<Long> enterpriseIds = enterpriseList.stream().map(Enterprise::getEnterpriseId).collect(Collectors.toList());
                List<Station> stationList =
                        stationService.list(new QueryWrapper<Station>().in("enterprise_id", enterpriseIds));
                for (Station ss : stationList) {
                    list.add(ss.getStationId() + "");
                }
                divideAccountsSettingDto.setStationIdList(list);
            } else {
                throw new CustomException("未创建油企");
            }
        }
        startPage();
        //payOrder.setStatus("1");
        List<DivideAccountsSettingDto> divideAccountsSettingList = payOrderService.queryDivideSettingList(divideAccountsSettingDto);

        return getDataTable(divideAccountsSettingList);

    }


    @GetMapping("/selectDivideAccountsDetail")
    @ApiOperation("查询分账详情")
    public DivideAccountsDetailVo selectDivideAccountsDetail(String uuid) {
        return payOrderService.selectDivideAccountsDetail(uuid);
    }

    @GetMapping("/selectDivideSettingDetail")
    @ApiOperation("查询分账设置详情")
    public DivideAccountsSettingDto selectDivideSettingDetail(String beginMmo, String stationId) {
        return payOrderService.selectDivideSettingDetail(beginMmo, stationId);
    }

    @GetMapping("/selectDivideSettingStatus")
    @ApiOperation("修改分账设置状态")
    public int selectDivideSettingStatus(String beginMmo, String status) {
        return payOrderService.selectDivideSettingStatus(beginMmo, status);
    }

    @GetMapping("/selectPayOrderList")
    public TableDataInfo selectPayOrderList(PayOrder payOrder) {
        /* List<String> list = deptService.levelDeptList(payOrder.getLevelId());
        if(list!=null && list.size()>0){
            payOrder.setStationIdList(list);
            payOrder.setStationId(null);
        }*/
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            if(CollectionUtil.isEmpty(stations)){
                return getDataTable(new ArrayList<>());
            }
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }

        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else {

        }
        startPage();
        //payOrder.setStatus("1");
        List<PayOrder> payOrderList = payOrderService.selectPayOrderList(payOrder);
        return getDataTable(payOrderList);
    }

    @ApiOperation(value = "创建分账设置", httpMethod = "POST")
    @PostMapping("/creationDivideSetting")
    public AjaxResult creationDivideSetting(@RequestBody DivideAccountsSettingDto divideAccountsSettingDto) {
        return payOrderService.creationDivideSetting(divideAccountsSettingDto);

    }

    @ApiOperation(value = "修改分账设置", httpMethod = "POST")
    @PostMapping("/updateDivideSetting")
    public AjaxResult updateDivideSetting(@RequestBody DivideAccountsSettingDto divideAccountsSettingDto) {
        return payOrderService.updateDivideSetting(divideAccountsSettingDto);

    }


    @ApiOperation(value = "删除分账设置传stationId和beginMmo", httpMethod = "POST")
    @PostMapping("/deleteByBeginMmo")
    public AjaxResult deleteByBeginMmo(@RequestBody DivideAccountsSettingDto divideAccountsSettingDto) {
        return payOrderService.deleteByBeginMmo(divideAccountsSettingDto);

    }


    /**
     * 查询订单，通过appuser 信息
     */
    @GetMapping("/selectPayOrderByAppUserInfo")
    public TableDataInfo selectPayOrderByAppUserInfo(SysAppUserInfo sysAppUserInfo) {
        startPage();
        LoginUser current = SecurityUtils.getLoginUser();
        PayOrder payOrder = new PayOrder();

        List<String> stationids = new ArrayList<>();
        if ("0".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(sysAppUserInfo.getStationId());
            List<Station> stations = stationService.selectStationList(station);
            for (Station station1 : stations) {
                stationids.add(station1.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(stationids);
            }
        } else if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            if(CollectionUtil.isEmpty(stations)){
                return getDataTable(new ArrayList<>());
            }
            for (Station station1 : stations) {
                stationids.add(station1.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(stationids);
            }
        } else if ("2".equals(current.getUser().getUserLevel())) {
            stationids.add(current.getUser().getStationId() + "");

        }

        payOrder.setConsumerId(sysAppUserInfo.getUserId());
        // payOrder.setStatus("1");
        List<PayOrder> payOrderList = payOrderService.selectPayOrderList(payOrder);
        return getDataTable(payOrderList);
    }

    /**
     * 查询订单支付列表
     */
    @GetMapping("/listInfo")
    public TableDataInfo listInfo(PayOrder payOrder) {
       /* List<String> list = deptService.levelDeptList(payOrder.getLevelId());
        if(list!=null && list.size()>0){
            payOrder.setStationIdList(list);
            payOrder.setStationId(null);
        }*/
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            if(CollectionUtil.isEmpty(stations)){
                return getDataTable(new ArrayList<>());
            }
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }

        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else {

        }
        //payOrder.setOrderType("1");
        //payOrder.setStatus("1");
        List<PayOrder> payOrderList = payOrderService.selectPayOrderList(payOrder);
        return getTable(payOrderList);
    }

    /**
     * 查询总金额，总升数
     *
     * @param payOrder
     * @return
     */
    @GetMapping("/selectDaySources")
    public AjaxResult selectDaySources(PayOrder payOrder) {
        /*List<String> list = deptService.levelDeptList(payOrder.getLevelId());
        if(list!=null && list.size()>0){
            payOrder.setStationIdList(list);
            payOrder.setStationId(null);
        }*/
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            if(CollectionUtil.isEmpty(stations)){
                return AjaxResult.success(new PayOrder());
            }
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }


        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else {

        }
        //payOrder.setStatus("1");
        //payOrder.setOrderType("1");
        PayOrder order = payOrderService.selectDaySources(payOrder);
        return AjaxResult.success(order);
    }


    /**
     * 查询总金额，总升数(针对加气平台的)
     *
     * @param payOrder
     * @return
     */
    @GetMapping("/selectLNGDaySources")
    public AjaxResult selectLNGDaySources(PayOrder payOrder) {
        /*List<String> list = deptService.levelDeptList(payOrder.getLevelId());
        if(list!=null && list.size()>0){
            payOrder.setStationIdList(list);
            payOrder.setStationId(null);
        }*/
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            if(CollectionUtil.isEmpty(stations)){
                return AjaxResult.success(new PayOrder());
            }
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }


        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else {

        }
        //payOrder.setStatus("1");
        //payOrder.setOrderType("1");
        PayOrder order = payOrderService.selectDaySources(payOrder);
        return AjaxResult.success(order);
    }

    /**
     * 查询总站下的合计数
     *
     * @param payOrder
     * @return
     */
    @GetMapping("/selectAllDaySources")
    public AjaxResult selectAllDaySources(PayOrder payOrder) {
       /* List<String> list = deptService.levelDeptList(payOrder.getLevelId());
        if(list!=null && list.size()>0){
            payOrder.setStationIdList(list);
            payOrder.setStationId(null);
        }*/
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        SysUser user = current.getUser();
        if (StringUtils.equals(UserConstants.LEVEL_TWO, user.getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(user.getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            if(CollectionUtil.isEmpty(stations)){
                return AjaxResult.success(new PayOrder());
            }
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (CollectionUtils.isNotEmpty(list)) {
                payOrder.setStationIdList(list);
            }

        } else if (StringUtils.equals(UserConstants.LEVEL_THREE, user.getUserLevel())) {
            payOrder.setStationId(user.getStationId());
            if (StaffUtil.isStaff(user)) {
                payOrder.setOilPersonnelId(String.valueOf(user.getUserId()));
            }
        }else if(SecurityUtils.isPartner()){
            EnterpriseAndStationVo itemIds = stationService.getItemIds(current.getUser());
            if(itemIds == null){
                throw new CustomException(UserConstants.NO_ENTERPRISE);
            }
            payOrder.setEnterpriseIdListForAuthor(itemIds.getEnterpriseIds());
            payOrder.setStationIdList(itemIds.getStationIdsStr());
        }
        //payOrder.setStatus("1");
        //payOrder.setOrderType("1");
        PayOrder order = null;
        BigDecimal totalAmt = BigDecimal.ZERO;  // 总金额
        Integer totalCountNum = 0;  // 总数量
        BigDecimal totalOrderLiters = BigDecimal.ZERO;  // 总订单升数
        BigDecimal totalQyAmt = BigDecimal.ZERO;  // 总qy金额
        // 获取当前时间七天前的时间点
        LocalDateTime sevenDaysAgo = LocalDateTime.now().minusDays(7);
        // 将字符串时间解析为LocalDateTime对象
        LocalDateTime beginTime = null;
        if (payOrder.getBeginTime() != null && !payOrder.getBeginTime().isEmpty()) {
            String beginDateTime = payOrder.getBeginTime();
            if (!beginDateTime.contains(":")) {
                // 不包含时间部分，添加默认的 "00:00:00"
                beginDateTime += " 00:00:00";
            }
            beginTime = LocalDateTime.parse(beginDateTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        }
// 如果beginTime为空，则查询全部对象；否则，根据beginTime的值判断查询对象
        if (beginTime == null) {
            order = payOrderService.selectAllDaySources(payOrder);
            PayOrder orderHistory = payOrderHistoryService.selectAllDaySources(payOrder);

            if (order != null) {
                if (order.getAmt() != null) {
                    totalAmt = totalAmt.add(order.getAmt());
                }
                if (order.getCountNum() != null) {
                    totalCountNum += order.getCountNum();
                }
                if (order.getOrderLiters() != null) {
                    totalOrderLiters = totalOrderLiters.add(order.getOrderLiters());
                }
                if (order.getQyAmt() != null) {
                    totalQyAmt = totalQyAmt.add(order.getQyAmt());
                }
            }

            if (orderHistory != null) {
                if (orderHistory.getAmt() != null) {
                    totalAmt = totalAmt.add(orderHistory.getAmt());
                }
                if (orderHistory.getCountNum() != null) {
                    totalCountNum += orderHistory.getCountNum();
                }
                if (orderHistory.getOrderLiters() != null) {
                    totalOrderLiters = totalOrderLiters.add(orderHistory.getOrderLiters());
                }
                if (orderHistory.getQyAmt() != null) {
                    totalQyAmt = totalQyAmt.add(orderHistory.getQyAmt());
                }
            }
        } else {
            if (beginTime.isAfter(sevenDaysAgo)) {
                order = payOrderService.selectAllDaySources(payOrder);
                if (order != null) {
                    if (order.getAmt() != null) {
                        totalAmt = totalAmt.add(order.getAmt());
                    }
                    if (order.getCountNum() != null) {
                        totalCountNum += order.getCountNum();
                    }
                    if (order.getOrderLiters() != null) {
                        totalOrderLiters = totalOrderLiters.add(order.getOrderLiters());
                    }
                    if (order.getQyAmt() != null) {
                        totalQyAmt = totalQyAmt.add(order.getQyAmt());
                    }
                }
            } else {
                order = payOrderService.selectAllDaySources(payOrder);
                if (order != null) {
                    if (order.getAmt() != null) {
                        totalAmt = totalAmt.add(order.getAmt());
                    }
                    if (order.getCountNum() != null) {
                        totalCountNum += order.getCountNum();
                    }
                    if (order.getOrderLiters() != null) {
                        totalOrderLiters = totalOrderLiters.add(order.getOrderLiters());
                    }
                    if (order.getQyAmt() != null) {
                        totalQyAmt = totalQyAmt.add(order.getQyAmt());
                    }
                }
                PayOrder orderHistory = payOrderHistoryService.selectAllDaySources(payOrder);
                if (orderHistory != null) {
                    if (orderHistory.getAmt() != null) {
                        totalAmt = totalAmt.add(orderHistory.getAmt());
                    }
                    if (orderHistory.getCountNum() != null) {
                        totalCountNum += orderHistory.getCountNum();
                    }
                    if (orderHistory.getOrderLiters() != null) {
                        totalOrderLiters = totalOrderLiters.add(orderHistory.getOrderLiters());
                    }
                    if (orderHistory.getQyAmt() != null) {
                        totalQyAmt = totalQyAmt.add(orderHistory.getQyAmt());
                    }
                }
            }
        }

        payOrder.setAmt(totalAmt);  // 设置总金额
        payOrder.setCountNum(totalCountNum);  // 设置总数量
        payOrder.setOrderLiters(totalOrderLiters);  // 设置总订单升数
        payOrder.setQyAmt(totalQyAmt);  // 设置总qy金额

        return AjaxResult.success(order);

    }

    /**
     * 查询总站下的合计数
     *
     * @param payOrder
     * @return
     */
    @GetMapping("/selectReceiveDaySources")
    public AjaxResult selectReceiveDaySources(PayOrder payOrder) {
       /* List<String> list = deptService.levelDeptList(payOrder.getLevelId());
        if(list!=null && list.size()>0){
            payOrder.setStationIdList(list);
            payOrder.setStationId(null);
        }*/
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        CustomerCardUseRecord customerCardUseRecord = new CustomerCardUseRecord();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            if(CollectionUtil.isEmpty(stations)){
                return AjaxResult.success(new PayOrder());
            }
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
                customerCardUseRecord.setStationIdList(list);
            }


        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
            customerCardUseRecord.setStationId(Integer.parseInt(current.getUser().getStationId() + ""));
        } else {

        }
        payOrder.setStatus("1");
        payOrder.setReceiveFalge("1");
        //payOrder.setStatus("1");
        //payOrder.setOrderType("1");
        PayOrder order = payOrderService.selectAllDaySources(payOrder);

        customerCardUseRecord.setUsageType("+");
        customerCardUseRecord.setPayType("wx");
        customerCardUseRecord.setStatus("1");
        customerCardUseRecord.setBeginTime(payOrder.getBeginTime());
        customerCardUseRecord.setEndTime(payOrder.getEndTime());
        CustomerCardUseRecord customerCardUseRecord1 = customerCardUseRecordService.listCZXFData(customerCardUseRecord);
        if (customerCardUseRecord1 != null && customerCardUseRecord1.getCzAmt() != null) {
            BigDecimal amt = BigDecimal.ZERO;
            if (order.getAmt() != null) {
                amt = order.getAmt().add(BigDecimal.valueOf(Double.valueOf(customerCardUseRecord1.getCzAmt())));
            } else {
                amt = BigDecimal.valueOf(Double.valueOf(customerCardUseRecord1.getCzAmt()));
            }
            order.setAmt(amt);
            order.setCzAmt(customerCardUseRecord1.getCzAmt());
        }
        return AjaxResult.success(order);
    }

    /**
     * 首页以时间查询，实收和升数
     *
     * @param payOrder
     * @return
     */
    @GetMapping("/homeSumQuery")
    @ApiOperation("首页接口")
    public AjaxResult homeSumQuery(PayOrder payOrder) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        if (payOrder.getBeginTime() != null && payOrder.getEndTime() != null) {
            // 将字符串转换为LocalDate类型

            LocalDate beginDate = LocalDate.parse(payOrder.getBeginTime(), formatter);
            LocalDate endDate = LocalDate.parse(payOrder.getEndTime(), formatter);

            // 计算两个日期之间的差值
            long daysBetween = ChronoUnit.DAYS.between(beginDate, endDate);

            // 如果差值超过一个月，返回失败
            if (daysBetween > 31) {
                return AjaxResult.error("仅可查询一个月");
            }
        } else {
            return AjaxResult.error("开始时间和结束时间不能为空");
        }
//        LocalDate date1 = LocalDate.parse(payOrder.getBeginTime());
//        LocalDate date2 = LocalDate.parse(payOrder.getEndTime());
        LocalDateTime date1 = LocalDateTime.parse(payOrder.getBeginTime(), formatter);
        LocalDateTime date2 = LocalDateTime.parse(payOrder.getEndTime(), formatter);
//        LocalDate currentDatenew = LocalDate.now(); // 获取当前日期
        LocalDateTime currentDatenew = LocalDateTime.now();
        LocalDateTime sixDaysAgo = currentDatenew.minusDays(6); // 获取当前日期往前6天的日期
        if (date1.isAfter(date2)) {
            return AjaxResult.error("开始时间不能在结束时间之后");
        }
//        if (date1.equals(date2)) {
//            LocalDateTime startTime = date1.atStartOfDay();
//            LocalDateTime endTime = date2.atTime(23, 59, 59);
//            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//            String formattedStartTime = startTime.format(formatter);
//            String formattedEndTime = endTime.format(formatter);
//            payOrder.setBeginTime(formattedStartTime);
//            payOrder.setEndTime(formattedEndTime);
//        }
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        SysUser user = current.getUser();
        Map<String, Object> paramsForRechange = new HashMap<String, Object>();
        HomeContext context = new HomeContext();
        XcxActualPaymentDto xcxActualPayment = new XcxActualPaymentDto();
        xcxActualPayment.setEnterpriseId(user.getEnterpriseId());
        XcxActualPaymentDto resultXcx = userService.xcxActualPaymentDetail(xcxActualPayment);
        if (StringUtils.equals(UserConstants.LEVEL_TWO, user.getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(user.getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            if(CollectionUtil.isEmpty(stations)){
                return AjaxResult.success(context);
            }
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (CollectionUtils.isNotEmpty(list)) {
                payOrder.setStationIdList(list);
            }
            payOrder.setEnterpriseId(user.getEnterpriseId());
            context.setIsShowAmt(resultXcx.getIsEnterprise());
            paramsForRechange.put("enterpriseId", user.getEnterpriseId());
        } else if (StringUtils.equals(UserConstants.LEVEL_THREE, user.getUserLevel())) {
            payOrder.setStationId(user.getStationId());
            paramsForRechange.put("stationId", user.getStationId());
            if (StaffUtil.isStaff(user)) {
                payOrder.setOilPersonnelId(String.valueOf(user.getUserId()));
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("stationId", user.getStationId());
                Map<String, Object> endTimeMap = classSettlementService.queryLastEndTime(params);
                // 员工权限 员工账号首页数据按当日全部或根据班结时间进行展示
                SysUser employeeShow = sysUserService.getById(user.getUserId());
                context.setIsShowAmt(resultXcx.getIsStaff());
                if (endTimeMap != null && !endTimeMap.isEmpty()
                        && Objects.nonNull(endTimeMap.get("classEndTime"))) {
                    if (EmployeeShowEnum.CLASS_TIME.getValue().equals(employeeShow.getEmployeeShow())) {
                        payOrder.setBeginTime(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", (Date) endTimeMap.get("classEndTime")));
                    }
                    log.info("员工权限首页请求参数：[{}]", JSONObject.toJSONString(payOrder));
                }
            } else {
                context.setIsShowAmt(resultXcx.getIsStation());
            }
        }else if(SecurityUtils.isPartner()){
            EnterpriseAndStationVo itemIds = stationService.getItemIds(current.getUser());
            List<Long> enterpriseIds = itemIds.getEnterpriseIds();
            if (enterpriseIds != null && enterpriseIds.size()>0) {
                payOrder.setEnterpriseIdListForAuthor(enterpriseIds);
            } else {
                throw new CustomException(UserConstants.NO_ENTERPRISE);
            }
        }


        //判断等级查询
        assignPayOrder(payOrder, user);

        // 油品销售数量
        List<OilSaleNumDto> oilSaleNumList = payOrderService.getOilSaleNumList(payOrder);

        // 会员数量
        MemberNumDto memberNum = appUserInfoService.selectMemberNum(payOrder);
        PayOrder sumPayOrder = null;
        PayOrder sevenPayOrder = null;
        if (date1.isAfter(sixDaysAgo)) {
            // 开始时间在当前时间往前6天内
            sumPayOrder = payOrderService.selectSumPayOrder(payOrder);
        } else {
            sumPayOrder = payOrderService.selectSumPayOrder(payOrder);
            sevenPayOrder = payOrderHistoryService.selectSumPayOrder(payOrder);
        }

        if (sumPayOrder != null && sevenPayOrder != null && sumPayOrder.getCountNum() != 0) {
            if (sevenPayOrder.getAmt() != null) {
                sumPayOrder.setAmt((sumPayOrder.getAmt() != null ? sumPayOrder.getAmt() : BigDecimal.ZERO).add(sevenPayOrder.getAmt()));
            }
            if (sevenPayOrder.getCountNum() != null) {
                sumPayOrder.setCountNum(sumPayOrder.getCountNum() + sevenPayOrder.getCountNum());
            }
            if (sevenPayOrder.getCyAmt() != null) {
                sumPayOrder.setCyAmt((sumPayOrder.getCyAmt() != null ? sumPayOrder.getCyAmt() : BigDecimal.ZERO).add(sevenPayOrder.getCyAmt()));
            }
            if (sevenPayOrder.getDiscountAmt() != null) {
                sumPayOrder.setDiscountAmt((sumPayOrder.getDiscountAmt() != null ? sumPayOrder.getDiscountAmt() : BigDecimal.ZERO).add(sevenPayOrder.getDiscountAmt()));
            }
            if (sevenPayOrder.getDiscountCouponAmt() != null) {
                sumPayOrder.setDiscountCouponAmt((sumPayOrder.getDiscountCouponAmt() != null ? sumPayOrder.getDiscountCouponAmt() : BigDecimal.ZERO).add(sevenPayOrder.getDiscountCouponAmt()));
            }
            if (sevenPayOrder.getOrderLiters() != null) {
                sumPayOrder.setOrderLiters(sumPayOrder.getOrderLiters().add(sevenPayOrder.getOrderLiters()));
            }
            if (sevenPayOrder.getQyAmt() != null) {
                sumPayOrder.setQyAmt((sumPayOrder.getQyAmt() != null ? sumPayOrder.getQyAmt() : BigDecimal.ZERO).add(sevenPayOrder.getQyAmt()));
            }
            if (sevenPayOrder.getReceivableAmt() != null) {
                sumPayOrder.setReceivableAmt(sumPayOrder.getReceivedAmt().add(sevenPayOrder.getReceivableAmt()));
            }
            if (sevenPayOrder.getReceivedAmt() != null) {
                sumPayOrder.setReceivedAmt(sumPayOrder.getReceivedAmt().add(sevenPayOrder.getReceivedAmt()));
            }
            if (sumPayOrder.getSsAmt() != null && sevenPayOrder.getSsAmt() != null) {
                BigDecimal ssamt1 = new BigDecimal(sumPayOrder.getSsAmt());
                BigDecimal ssamt2 = new BigDecimal(sevenPayOrder.getSsAmt());
                sumPayOrder.setSsAmt(ssamt1.add(ssamt2).toString());
            }
        } else if (sumPayOrder != null && sevenPayOrder != null && sumPayOrder.getCountNum() == 0) {
            sumPayOrder = new PayOrder();

            if (sevenPayOrder.getAmt() != null) {
                sumPayOrder.setAmt(sevenPayOrder.getAmt());
            }
            if (sevenPayOrder.getCountNum() != null) {
                sumPayOrder.setCountNum(sevenPayOrder.getCountNum());
            }
            if (sevenPayOrder.getCyAmt() != null) {
                sumPayOrder.setCyAmt(sevenPayOrder.getCyAmt());
            }
            if (sevenPayOrder.getDiscountAmt() != null) {
                sumPayOrder.setDiscountAmt(sevenPayOrder.getDiscountAmt());
            }
            if (sevenPayOrder.getDiscountCouponAmt() != null) {
                sumPayOrder.setDiscountCouponAmt(sevenPayOrder.getDiscountCouponAmt());
            }
            if (sevenPayOrder.getOrderLiters() != null) {
                sumPayOrder.setOrderLiters(sevenPayOrder.getOrderLiters());
            }
            if (sevenPayOrder.getQyAmt() != null) {
                sumPayOrder.setQyAmt(sevenPayOrder.getQyAmt());
            }
            if (sevenPayOrder.getReceivableAmt() != null) {
                sumPayOrder.setReceivableAmt(sevenPayOrder.getReceivableAmt());
            }
            if (sevenPayOrder.getReceivedAmt() != null) {
                sumPayOrder.setReceivedAmt(sevenPayOrder.getReceivedAmt());
            }
            if (sevenPayOrder.getSsAmt() != null) {
                sumPayOrder.setSsAmt(sevenPayOrder.getSsAmt());
            }

        }

        paramsForRechange.put("createStartTime", payOrder.getBeginTime());
        paramsForRechange.put("createEndTime", payOrder.getEndTime());
        paramsForRechange.put("stationIdList", payOrder.getStationIdList());
        paramsForRechange.put("enterpriseId", payOrder.getEnterpriseId());
        paramsForRechange.put("enterpriseIdListForAuthor", payOrder.getEnterpriseIdListForAuthor());
        BigDecimal rechargeAmt = classSettlementService.homeRechargeReceivedAmt(paramsForRechange);
        sumPayOrder.setRechargeAmt(rechargeAmt);

        List<ClassSettlementCard> rechargeAmtSeven = classSettlementService.homeRechargeReceivedAmtSeven(paramsForRechange);

        // 七日趋势图
        List<Map<String, Object>> series = payOrderService.homeSevenSumQuery(payOrder, rechargeAmtSeven);


        List<Map<String, Object>> dataList = payOrderService.homePaymentSumQuery(payOrder);


        if (dataList.size() == 0) {
            context = new HomeContext("", "", "", sumPayOrder.getCountNum(), dataList, series, oilSaleNumList, memberNum);

        } else {

            if (sumPayOrder != null) {


                if (sumPayOrder.getOrderLiters() != null) {
                    context.setTotalRefuelingAmt(sumPayOrder.getOrderLiters().toString());
                }

                if (sumPayOrder.getReceivableAmt() != null) {
                    context.setRefuelingAmt(sumPayOrder.getReceivableAmt().toString());
                    context.setRechargeAndPayAmt(rechargeAmt.add(sumPayOrder.getReceivableAmt()));
                } else {
                    context.setRechargeAndPayAmt(rechargeAmt);
                }

                if (sumPayOrder.getCountNum() != null) {
                    context.setOrderAmt(sumPayOrder.getCountNum());
                }
                if (sumPayOrder.getDiscountAmt() != null && sumPayOrder.getDiscountCouponAmt() != null) {
                    context.setTotalDiscountAmt(sumPayOrder.getDiscountAmt().add(sumPayOrder.getDiscountCouponAmt()).setScale(2, RoundingMode.DOWN).toString());
                }
                context.setPayTypePercentage(dataList);
                context.setSeries(series);
                context.setOilSaleNumList(oilSaleNumList);
                context.setMemberNum(memberNum);
                context.setRechargeAmt(rechargeAmt);

                if (sumPayOrder.getSsAmt() != null) {
                    context.setSsAmt(sumPayOrder.getSsAmt().toString());
                }

            } else {
                context = new HomeContext("", "", "", sumPayOrder.getCountNum(), dataList, series, oilSaleNumList, memberNum);
            }

        }

        return AjaxResult.success(context);

    }

    /**
     * 查询总金额，总升数
     *
     * @param payOrder
     * @return
     */
    @GetMapping("/selectSumPayOrder")
    public AjaxResult selectSumPayOrder(PayOrder payOrder) {
        /*List<String> list = deptService.levelDeptList(payOrder.getLevelId());
        if(list!=null && list.size()>0){
            payOrder.setStationIdList(list);
            payOrder.setStationId(null);
        }*/
        if (payOrder.getPartner() != null && !payOrder.getPartner().isEmpty()) {
            SysUser byId = sysUserService.getById(Long.valueOf(payOrder.getPartner()));
            EnterpriseAndStationVo itemIds = stationService.getItemIds(byId);
            if (itemIds != null && itemIds.getEnterpriseIds() != null &&itemIds.getEnterpriseIds().size()>0) {
                payOrder.setEnterpriseIdListForAuthor(itemIds.getEnterpriseIds());

            } else if(payOrder.getPartner().equals("1")){ }else {
                PayOrder reorder = new PayOrder();
                return AjaxResult.success(reorder);
            }
        }
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            if(CollectionUtil.isEmpty(stations)){
                return AjaxResult.success(new PayOrder());
            }
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }
        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder=   payOrderService.timeSetting(payOrder,current.getUser().getStationId());

            payOrder.setStationId(current.getUser().getStationId());

            if (StaffUtil.isStaff(current.getUser())) {
                payOrder.setOilPersonnelId(String.valueOf(current.getUser().getUserId()));
            } else {
                Station station = stationService.selectStationById(current.getUser().getStationId());
                String showPayWayIds = station.getShowPayWayIds();
                if (showPayWayIds != null) {
                    String[] idArray = showPayWayIds.split(","); // 拆分成字符串数组
                    List<Long> idList = new ArrayList<>();
                    for (int i = 0; i < idArray.length; i++) {
                        String id = idArray[i].trim();
                        if (!id.isEmpty()) {
                            idList.add(Long.parseLong(id));
                        }
                    }
                    payOrder.setPayWayIdList(idList);
                }
            }
        } else if (SecurityUtils.isPartner()){
            EnterpriseAndStationVo itemIds = stationService.getItemIds(current.getUser());
            if(itemIds.getStationIds() == null){
                return AjaxResult.error("请创建油站");
            }
            payOrder.setStationIdList(itemIds.getStationIdsStr());

        }
        assignPayOrder(payOrder, current.getUser());
        LocalDate today = LocalDate.now();
        LocalDate tomorrow = today.plusDays(1);

        LocalDateTime startTime = today.atStartOfDay();
        LocalDateTime endTime = tomorrow.atStartOfDay();

        String currentBeginTime = payOrder.getBeginTime();
        String currentEndTime = payOrder.getEndTime();

        if (currentBeginTime != null && !currentBeginTime.isEmpty() && currentEndTime != null && !currentEndTime.isEmpty()) {
            LocalDateTime parsedBeginTime = LocalDateTime.parse(currentBeginTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            LocalDateTime parsedEndTime = LocalDateTime.parse(currentEndTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

            if (startTime.compareTo(parsedBeginTime) > 0) {
                String formattedStartTime = startTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                payOrder.setBeginTime(formattedStartTime);
            }

            if (endTime.compareTo(parsedEndTime) < 0) {
                String formattedEndTime = endTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                payOrder.setEndTime(formattedEndTime);
            }
        } else {
            String formattedStartTime = startTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            payOrder.setBeginTime(formattedStartTime);
            String formattedEndTime = endTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            payOrder.setEndTime(formattedEndTime);
        }
        PayOrder order = payOrderService.selectSumPayOrder(payOrder);
        return AjaxResult.success(order);
    }

    /***
     * 根据油品分类，查询油品的总金额，总升数
     * @param payOrder
     * @return
     */
    @GetMapping("/selectOilTypeSources")
    public TableDataInfo selectOilTypeSources(PayOrder payOrder) {
       /* List<String> list = deptService.levelDeptList(payOrder.getLevelId());
        if(list!=null && list.size()>0){
            payOrder.setStationIdList(list);
            payOrder.setStationId(null);
        }*/
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            if(CollectionUtil.isEmpty(stations)){
                return getTable(new ArrayList<>());
            }
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }


        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else {

        }
        //payOrder.setStatus("1");
        //payOrder.setOrderType("1");
        List<PayOrder> orderList = payOrderService.selectOilTypeSources(payOrder);
        return getTable(orderList);
    }

    /***
     * 根据油品分类，查询油品的总金额，总升数，查询所有订单信息
     * @param payOrder
     * @return
     */
    @GetMapping("/selectAllOilTypeSources")
    public TableDataInfo selectAllOilTypeSources(PayOrder payOrder) {
       /* List<String> list = deptService.levelDeptList(payOrder.getLevelId());
        if(list!=null && list.size()>0){
            payOrder.setStationIdList(list);
            payOrder.setStationId(null);
        }*/
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        SysUser user = current.getUser();
        if (StringUtils.equals(UserConstants.LEVEL_TWO, user.getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(user.getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            if(CollectionUtil.isEmpty(stations)){
                return getTable(new ArrayList<>());
            }
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (CollectionUtils.isNotEmpty(list)) {
                payOrder.setStationIdList(list);
            }

        } else if (StringUtils.equals(UserConstants.LEVEL_THREE, user.getUserLevel())) {
            payOrder.setStationId(user.getStationId());
            if (StaffUtil.isStaff(user)) {
                payOrder.setOilPersonnelId(String.valueOf(user.getUserId()));
            }
        } else if ("7".equals(user.getUserLevel())) {
            List<Enterprise> enterpriseList =
                    enterpriseService.list(new QueryWrapper<Enterprise>().in("author_id", user.getUserId()));
            if (enterpriseList != null && enterpriseList.size() > 0) {
                List<Long> enterpriseIds = enterpriseList.stream().map(Enterprise::getEnterpriseId).collect(Collectors.toList());
                payOrder.setEnterpriseIdListForAuthor(enterpriseIds);
                for (Long enterId : enterpriseIds) {
                    Station station = new Station();
                    station.setEnterpriseId(enterId);
                    List<Station> stations = stationService.selectStationList(station);
                    for (Station ss : stations) {
                        list.add(ss.getStationId() + "");
                    }
                }
                if (CollectionUtils.isNotEmpty(list)) {
                    payOrder.setStationIdList(list);
                }
            } else {
                throw new CustomException(UserConstants.NO_ENTERPRISE);
            }
        }
        //payOrder.setStatus("1");
        // payOrder.setOrderType("1");
        List<PayOrder> orderList = payOrderService.selectAllOilTypeSources(payOrder);
        return getTable(orderList);
    }


    /***
     * 根据油品分类，查询油品的总金额，总升数
     * @param payOrder
     * @return
     */
    @GetMapping("/dayOilTypeSources")
    public TableDataInfo dayOilTypeSources(PayOrder payOrder) {
        /*List<String> list = deptService.levelDeptList(payOrder.getLevelId());
        if(list!=null && list.size()>0){
            payOrder.setStationIdList(list);
            payOrder.setStationId(null);
        }*/
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            if(CollectionUtil.isEmpty(stations)){
                return getTable(new ArrayList<>());
            }
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }


        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else {

        }
        //payOrder.setStatus("1");
        //payOrder.setOrderType("1");
        List<PayOrder> orderList = payOrderService.dayOilTypeSources(payOrder);
        return getTable(orderList);
    }

    /***
     * 根据油品分类，查询油品的总金额，总升数
     * @param payOrder
     * @return
     */
    @GetMapping("/dayAllOilTypeSources")
    public TableDataInfo dayAllOilTypeSources(PayOrder payOrder) {
       /* List<String> list = deptService.levelDeptList(payOrder.getLevelId());
        if(list!=null && list.size()>0){
            payOrder.setStationIdList(list);
            payOrder.setStationId(null);
        }*/
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            if(CollectionUtil.isEmpty(stations)){
                return getTable(new ArrayList<>());
            }
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }


        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else {

        }
        //payOrder.setStatus("1");
        //payOrder.setOrderType("1");
        List<PayOrder> orderList = payOrderService.dayAllOilTypeSources(payOrder);
        return getTable(orderList);
    }

    /***
     * 根据油品分类，查询油品的总金额，总升数
     * @param payOrder
     * @return
     */
    @GetMapping("/selectOverViewData")
    public AjaxResult selectOverViewData(PayOrder payOrder) {
       /* List<String> list = deptService.levelDeptList(payOrder.getLevelId());
        if(list!=null && list.size()>0){
            payOrder.setStationIdList(list);
            payOrder.setStationId(null);
        }*/
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            if(CollectionUtil.isEmpty(stations)){
                return AjaxResult.success(new PayOrder());
            }
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }


        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else {
            Station station = new Station();
            List<Station> stations = stationService.selectStationList(station);
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }

        }
        //payOrder.setStatus("1");
        //payOrder.setOrderType("1");
        PayOrder order = payOrderService.selectOverViewData(payOrder);
        return AjaxResult.success(order);
    }

    /***
     * 根据油品分类，查询油品的总金额，总升数(包括已经退款的)
     * @param payOrder
     * @return
     */
    @GetMapping("/selectAllOverViewData")
    public AjaxResult selectAllOverViewData(PayOrder payOrder) {
        /*List<String> list = deptService.levelDeptList(payOrder.getLevelId());
        if(list!=null && list.size()>0){
            payOrder.setStationIdList(list);
            payOrder.setStationId(null);
        }*/
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            if(CollectionUtil.isEmpty(stations)){
                return AjaxResult.success(new PayOrder());
            }
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }


        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else {
            Station station = new Station();
            List<Station> stations = stationService.selectStationList(station);
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }

        }
        //payOrder.setStatus("1");
        //payOrder.setOrderType("1");
        PayOrder order = payOrderService.selectAllOverViewData(payOrder);
        return AjaxResult.success(order);
    }

    /**
     * 月报数据详细
     */
    @GetMapping("/selectDayReportDetail")
    public TableDataInfo selectDayReportDetail(PayOrder payOrder) {
       /* List<String> list = deptService.levelDeptList(payOrder.getLevelId());
        if(list!=null && list.size()>0){
            payOrder.setStationIdList(list);
            payOrder.setStationId(null);
        }*/
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            if(CollectionUtil.isEmpty(stations)){
                return getDataTable(new ArrayList<>());
            }
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }


        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else {
            Station station = new Station();
            List<Station> stations = stationService.selectStationList(station);
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }

        }
        //默认当前登陆人的ID 5冯总油站
        startPage();
        //payOrder.setStatus("1");
        //payOrder.setOrderType("1");
        List<PayOrder> orderList = payOrderService.selectDayReport(payOrder);
        return getDataTable(orderList);
    }

    /**
     * 月报数据详细
     */
    @GetMapping("/selectAllDayReportDetail")
    public TableDataInfo selectAllDayReportDetail(PayOrder payOrder) {
        /*List<String> list = deptService.levelDeptList(payOrder.getLevelId());
        if(list!=null && list.size()>0){
            payOrder.setStationIdList(list);
            payOrder.setStationId(null);
        }*/
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        SysUser user = current.getUser();
        if (StringUtils.equals(UserConstants.LEVEL_TWO, user.getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(user.getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            if(CollectionUtil.isEmpty(stations)){
                return getDataTable(new ArrayList<>());
            }
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (CollectionUtils.isNotEmpty(list)) {
                payOrder.setStationIdList(list);
            }

        } else if (StringUtils.equals(UserConstants.LEVEL_THREE, user.getUserLevel())) {
            payOrder.setStationId(user.getStationId());
            if (StaffUtil.isStaff(user)) {
                payOrder.setOilPersonnelId(String.valueOf(user.getUserId()));
            }
        } else if ("7".equals(user.getUserLevel())) {
            List<Enterprise> enterpriseList =
                    enterpriseService.list(new QueryWrapper<Enterprise>().in("author_id", user.getUserId()));
            if (enterpriseList != null && enterpriseList.size() > 0) {
                List<Long> enterpriseIds = enterpriseList.stream().map(Enterprise::getEnterpriseId).collect(Collectors.toList());
                payOrder.setEnterpriseIdListForAuthor(enterpriseIds);
                for (Long enterId : enterpriseIds) {
                    Station station = new Station();
                    station.setEnterpriseId(enterId);
                    List<Station> stations = stationService.selectStationList(station);
                    for (Station ss : stations) {
                        list.add(ss.getStationId() + "");
                    }
                }
                if (CollectionUtils.isNotEmpty(list)) {
                    payOrder.setStationIdList(list);
                }
            } else {
                throw new CustomException(UserConstants.NO_ENTERPRISE);
            }
        }
        //默认当前登陆人的ID 5冯总油站
        startPage();
        //payOrder.setStatus("1");
        //payOrder.setOrderType("1");
        List<PayOrder> orderList = payOrderService.selectAllDayReport(payOrder);
        return getDataTable(orderList);
    }

    /***
     * 根据油品分类，查询油品的总金额，总升数
     * @param payOrder
     * @return
     */
    @GetMapping("/selectDayReport")
    public TableDataInfo selectDayReport(PayOrder payOrder) {
        /*List<String> list = deptService.levelDeptList(payOrder.getLevelId());
        if(list!=null && list.size()>0){
            payOrder.setStationIdList(list);
            payOrder.setStationId(null);
        }*/
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            if(CollectionUtil.isEmpty(stations)){
                return getTable(new ArrayList<>());
            }
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }


        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else {
            Station station = new Station();
            List<Station> stations = stationService.selectStationList(station);
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }

        }
        //payOrder.setStatus("1");
        //payOrder.setOrderType("1");
        List<PayOrder> orderList = payOrderService.selectDayReport(payOrder);
        return getTable(orderList);
    }

    /**
     * 导出订单支付列表
     */
    @Log(title = "订单支付", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(PayOrder payOrder) {
 /* List<String> list = deptService.levelDeptList(payOrder.getLevelId());
        if(list!=null && list.size()>0){
            payOrder.setStationIdList(list);
            payOrder.setStationId(null);
        }*/
        if (payOrder.getPartner() != null && !payOrder.getPartner().isEmpty()) {
            SysUser byId = sysUserService.getById(Long.valueOf(payOrder.getPartner()));
            EnterpriseAndStationVo itemIds = stationService.getItemIds(byId);
            if (itemIds != null && itemIds.getEnterpriseIds() != null &&itemIds.getEnterpriseIds().size()>0) {
                payOrder.setEnterpriseIdListForAuthor(itemIds.getEnterpriseIds());

            }else if(payOrder.getPartner().equals("1")){ } else {
                List<String> alist = new ArrayList<>();
                ExcelUtil<PayOrder> util = new ExcelUtil<PayOrder>(PayOrder.class);
                return util.importTemplateExcel("订单信息");
            }
        }
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            if(CollectionUtil.isEmpty(stations)){
                return AjaxResult.error("未查询到油站信息");
            }
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }

        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());

            if (StaffUtil.isStaff(current.getUser())) {
                payOrder.setOilPersonnelId(String.valueOf(current.getUser().getUserId()));
            } else {
                Station station = stationService.selectStationById(current.getUser().getStationId());
                String showPayWayIds = station.getShowPayWayIds();
                if (showPayWayIds != null) {
                    String[] idArray = showPayWayIds.split(","); // 拆分成字符串数组
                    List<Long> idList = new ArrayList<>();
                    for (int i = 0; i < idArray.length; i++) {
                        String id = idArray[i].trim();
                        if (!id.isEmpty()) {
                            idList.add(Long.parseLong(id));
                        }
                    }
                    payOrder.setPayWayIdList(idList);
                }
            }
        } else if ("7".equals(current.getUser().getUserLevel())) {
            List<Enterprise> enterpriseList =
                    enterpriseService.list(new QueryWrapper<Enterprise>().in("author_id", current.getUser().getUserId()));
            if (enterpriseList != null && enterpriseList.size() > 0) {
                List<Long> enterpriseIds = enterpriseList.stream().map(Enterprise::getEnterpriseId).collect(Collectors.toList());
                List<Station> stationList =
                        stationService.list(new QueryWrapper<Station>().in("enterprise_id", enterpriseIds));
                for (Station ss : stationList) {
                    list.add(ss.getStationId() + "");
                }
                if (list != null && list.size() > 0) {
                    payOrder.setStationIdList(list);
                }else{
                    throw new CustomException("没有油站");
                }

            } else {
                throw new CustomException("未创建油企");
            }
        }
        assignPayOrder(payOrder, current.getUser());

        LocalDate today = LocalDate.now();
        LocalDate tomorrow = today.plusDays(1);

        LocalDateTime startTime = today.atStartOfDay();
        LocalDateTime endTime = tomorrow.atStartOfDay();

        String currentBeginTime = payOrder.getBeginTime();
        String currentEndTime = payOrder.getEndTime();

        if (currentBeginTime != null && !currentBeginTime.isEmpty() && currentEndTime != null && !currentEndTime.isEmpty()) {
            LocalDateTime parsedBeginTime = LocalDateTime.parse(currentBeginTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            LocalDateTime parsedEndTime = LocalDateTime.parse(currentEndTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

            if (startTime.compareTo(parsedBeginTime) > 0) {
                String formattedStartTime = startTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                payOrder.setBeginTime(formattedStartTime);
            }

            if (endTime.compareTo(parsedEndTime) < 0) {
                String formattedEndTime = endTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                payOrder.setEndTime(formattedEndTime);
            }
        } else {
            String formattedStartTime = startTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            payOrder.setBeginTime(formattedStartTime);
            String formattedEndTime = endTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            payOrder.setEndTime(formattedEndTime);
        }



//        List<PayOrder> payOrderList = payOrderService.selectAllPayOrderList(payOrder);
        //List<PayOrder> payOrderList = payOrderService.selectPayOrderList(payOrder);
        List<PayOrder> payOrderList = new ArrayList<>();
        List<PayOrderExport> payOrderExportList = new ArrayList<>();
        if (SecurityUtils.isAdmin(current.getUser().getUserId())||current.getUser().getUserLevel().equals("7")) {
            payOrderExportList = payOrderService.selectPayOrderAndWithdrawalAmountExportList(payOrder);
        }else{
            payOrderList = payOrderService.selectPayOrderAndWithdrawalAmountList(payOrder);
        }
        //组装合伙人
//        List<Long> collect = payOrderList.stream().map(PayOrder::getStationId).collect(Collectors.toList());
//        SysUser sysUser = new SysUser();
//        List<String> collect2 = collect.stream().map(String::valueOf).collect(Collectors.toList());
//        sysUser.setStationIdList(collect2);
//        List<SysUser> sysUsers = sysUserService.selectUserList(sysUser);
//        Map<Long, List<SysUser>> collect3 = sysUsers.stream().collect(Collectors.groupingBy(SysUser::getStationId));
//        //Map<Long, String> collect1 = sysUsers.stream().collect(Collectors.toMap(SysUser::getStationId, SysUser::getCreateBy));
//        for (PayOrder order : payOrderList) {
//            order.setPartner(collect3.get(order.getStationId()).get(1).getCreateBy());
//        }


            if (SecurityUtils.isAdmin(current.getUser().getUserId())||current.getUser().getUserLevel().equals("7")) {
                if (payOrderExportList != null && !payOrderExportList.isEmpty()) {
                } else {
                    // payOrderList 为空，执行其他操作或给出提示
                    ExcelUtil<PayOrder> util = new ExcelUtil<PayOrder>(PayOrder.class);
                    return util.importTemplateExcel("订单信息");

                }
                ExcelUtil<PayOrderExport> util = new ExcelUtil<PayOrderExport>(PayOrderExport.class);
                return util.exportExcel(payOrderExportList, "order");
            }else{
                if (payOrderList != null && !payOrderList.isEmpty()) {
                } else {
                    // payOrderList 为空，执行其他操作或给出提示
                    ExcelUtil<PayOrder> util = new ExcelUtil<PayOrder>(PayOrder.class);
                    return util.importTemplateExcel("订单信息");

                }
                ExcelUtil<PayOrder> util = new ExcelUtil<PayOrder>(PayOrder.class);
                return util.exportExcel(payOrderList, "order");
            }

    }


    /**
     * 获取订单支付详细信息
     */
    @GetMapping(value = "/{orderId}")
    public AjaxResult getInfo(@PathVariable("orderId") Long orderId) {
        return AjaxResult.success(payOrderService.selectPayOrderById(orderId));
    }


    /**
     * 根据上级集团的信息判断当前的用户是否进行审核
     */
    @PostMapping(value = "/applyExaminRefund")
    public AjaxResult applyExaminRefund(@RequestBody PayOrder payOrder) {
        LoginUser currentUser = SecurityUtils.getLoginUser();
        PayOrder payOrder1 = payOrderService.selectPayOrderById(payOrder.getOrderId());
        Date date = new Date();
        Calendar rightNow = Calendar.getInstance();
        rightNow.setTime(date);
        rightNow.add(Calendar.DAY_OF_YEAR, -2);//两天以前的订单不允许退款
        Date dt1 = rightNow.getTime();


        if (!"1".equals(payOrder1.getStatus())) {
            return AjaxResult.error("当前订单不能进行退款");
        }
/*        if ("dzk".equals(payOrder1.getPayType())) {
            return AjaxResult.error("电子卡的订单不能进行退款");
        }*/
        //现金退款功能
        //        if("xj".equals(payOrder1.getPayType())){
//            return AjaxResult.error("现金的订单不能进行退款");
//        }
//        if(!payOrder1.getPayDate().after(dt1)){
//            return AjaxResult.error("时间过长不允许退款");
//        }
        int i = 0;
        try {
            List<PayOrder> payOrderList = new ArrayList<>();
            payOrderList.add(payOrder1);
            if (payOrder1.getOrderMergeNo() != null) {
                payOrderList = payOrderService.getPayOrderListByOrderMergeNo(payOrder1.getOrderMergeNo());
            }
            Date now = new Date();
            Long userId = currentUser.getUser().getUserId();
            payOrderList.forEach(order -> {
                order.setRefundUser(userId);
                order.setRefundDate(now);
                order.setExaminStatus("1");
                payOrderService.updatePayOrder(order);
            });
            return AjaxResult.success(1);
        } catch (Exception e) {
            log.error("申请退款异常{}", e.getMessage());
            return AjaxResult.success(0);
        }


    }
    /**
     * 订单申请退款，重新申请退款
     */
    /*@PostMapping(value = "/applyRefund")
    public AjaxResult applyRefund(@RequestBody PayOrder payOrder)
    {
        if(!"1".equals(payOrder.getStatus())){
            return AjaxResult.error("当前订单不能进行退款");
        }
        if(!("0".equals(payOrder.getExaminStatus())||payOrder.getExaminStatus()==null||"3".equals(payOrder.getExaminStatus()))){
            return AjaxResult.error("当前订单不能进行退款");
        }
        int i=0;
        LoginUser currentUser = SecurityUtils.getLoginUser();
        payOrder.setRefundUser(currentUser.getUser().getUserId());
        payOrder.setRefundDate( new Date());
        payOrder.setExaminStatus("1");
        i=payOrderService.updatePayOrder(payOrder);
        return AjaxResult.success(i);
    }*/

    /**
     * 重新申请退款
     */
    /*@PostMapping(value = "/reapplyRefund")
    public AjaxResult reapplyRefund(@RequestBody PayOrder payOrder)
    {
        if(!"1".equals(payOrder.getStatus())){
            return AjaxResult.error("当前订单不能进行退款");
        }
        if(!("3".equals(payOrder.getExaminStatus()))){
            return AjaxResult.error("当前订单不能进行退款");
        }
        int i=0;
        LoginUser currentUser = SecurityUtils.getLoginUser();
        payOrder.setRefundUser(currentUser.getUser().getUserId());
        payOrder.setRefundDate( new Date());
        payOrder.setExaminStatus("1");
        i=payOrderService.updatePayOrder(payOrder);
        return AjaxResult.success(i);
    }*/

    /**
     * 撤回申请
     */
    @PostMapping(value = "/recallApplyRefund")
    public AjaxResult recallApplyRefund(@RequestBody PayOrder payOrder) {

        int i = 0;
        LoginUser currentUser = SecurityUtils.getLoginUser();
        PayOrder payOrder1 = payOrderService.selectPayOrderById(payOrder.getOrderId());
        if (!"1".equals(payOrder1.getStatus())) {
            return AjaxResult.error("当前订单不能撤回申请");
        }
        try {
            List<PayOrder> payOrderList = new ArrayList<>();
            payOrderList.add(payOrder1);
            if(payOrder1.getOrderMergeNo()!=null){
                payOrderList = payOrderService.getPayOrderListByOrderMergeNo(payOrder1.getOrderMergeNo());
            }
            Date now = new Date();
            Long userId = currentUser.getUser().getUserId();
            payOrderList.forEach(order->{
                order.setRefundUser(userId);
                order.setRefundDate(now);
                order.setExaminStatus("0");
                payOrderService.updatePayOrder(order);
            });
            return AjaxResult.success(1);
        } catch (Exception e) {
            log.error("撤回申请异常{}", e.getMessage());
            return AjaxResult.success(0);
        }
    }

    /**
     * 审核通过
     */
    @PostMapping(path = {"/examinRefundSuccess", "/anny/examinRefundSuccess/{timestamp}/{sign}"})
    public AjaxResult examinRefundSuccess(@RequestBody PayOrder payOrder,
                                          @RequestParam(required = false, defaultValue = "") Long userId) {
        PayOrder payOrderThis = payOrderService.selectPayOrderById(payOrder.getOrderId());
        if (!"1".equals(payOrderThis.getStatus())) {
            return AjaxResult.error("当前订单不能进行退款");
        }
        if (!("1".equals(payOrderThis.getExaminStatus()) || "4".equals(payOrderThis.getExaminStatus()))) {
            return AjaxResult.error("当前订单不能进行退款");
        }
        int i = 0;

        //LoginUser currentUser = SecurityUtils.getLoginUser();
       /* if("0".equals(currentUser.getUser().getDept().getRefundExaminStatus())){
            return AjaxResult.error("当前集团未设置审核权限");
        }*/
        LoginUser user;
        if (userId != null) {
            user = new LoginUser();
            SysUser sysUser = new SysUser();
            sysUser.setUserId(userId);
            user.setUser(sysUser);
        } else {
            user = SecurityUtils.getLoginUser();
        }
        try {
            return AjaxResult.success(payOrderService.examinRefundSuccess(payOrderThis, user));
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }

    }

    /**
     * 审核驳回
     */
    @PostMapping(value = "/examinRefundBack")
    public AjaxResult examinRefundBack(@RequestBody PayOrder payOrder) {

        PayOrder payOrder1 = payOrderService.selectPayOrderById(payOrder.getOrderId());
        if (!"1".equals(payOrder1.getStatus())) {
            return AjaxResult.error("当前订单不能进行退款");
        }
        if (!"1".equals(payOrder1.getExaminStatus())) {
            return AjaxResult.error("当前订单不能进行退款");
        }

        int i = 0;
        try {
            List<PayOrder> payOrderList = new ArrayList<>();
            payOrderList.add(payOrder1);
            if (payOrder1.getOrderMergeNo() != null) {
                payOrderList = payOrderService.getPayOrderListByOrderMergeNo(payOrder1.getOrderMergeNo());
            }

            LoginUser currentUser = SecurityUtils.getLoginUser();
            Long userId = currentUser.getUser().getUserId();
            Date now = new Date();
            for (PayOrder order : payOrderList) {

                order.setExaminUser(userId);
                order.setExaminDate(now);
                order.setExaminStatus("3");
                i += payOrderService.updatePayOrder(order);
            }
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success(i);
    }


    /**
     * 订单退款
     */
    @GetMapping(value = "/refund/{orderId}")
    public AjaxResult refund(@PathVariable("orderId") Long orderId) {
        int i = 0;
        PayOrder payOrder = new PayOrder();
        PayOrder payOrder1 = payOrderService.selectPayOrderById(orderId);
        if (payOrder1.getStatus().equals("2")) {
            return AjaxResult.error("已经被退款，不能重复退款");
        }
        LoginUser currentUser = SecurityUtils.getLoginUser();

        StationBalanceChange stationBalanceChange = new StationBalanceChange();
        stationBalanceChange.setAmt(payOrder1.getAmt());
        stationBalanceChange.setStationId(payOrder1.getStationId());
        stationBalanceChange.setType("+");
        stationBalanceChange.setCreateBy(currentUser.getUser().getUserId() + "");

        Long deptId = payOrder1.getStationId();
        SysDept dept1 = deptService.selectDeptById(deptId);
        SysDept dept = new SysDept();
        Float Balance1 = Float.parseFloat(dept1.getBalance().toString());
        Float value = Float.parseFloat(payOrder1.getAmt().toString());
        stationBalanceChange.setNowAmt(dept1.getBalance());
        dept.setDeptId(deptId);
        dept.setBalance(BigDecimal.valueOf(Balance1 + value));
        i = deptService.updateDept(dept);
        if (i != 0) {
            payOrder.setOrderId(orderId);
            payOrder.setStatus("2");//设置为已退款
            stationBalanceChangeService.insertStationBalanceChange(stationBalanceChange);
            i = payOrderService.updatePayOrder(payOrder);

        }

        if (i == 0) {
            return AjaxResult.error();
        }
        return AjaxResult.success(i);
    }


    /**
     * 订单退款
     */
    @PostMapping(value = "/sxfRefund")
    public AjaxResult sxfRefund(@RequestBody PayOrder payOrder) {

        try {
            sendSxfRefund(payOrder);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success(1);
    }

    public SysRespon sendSxfRefund(PayOrder payOrder) throws Exception {

        SysRespon respon = new SysRespon();
        SysDept dept = deptService.selectDeptById(payOrder.getStationId());
        Random random = new Random();
        String result1 = "";
        for (int i = 0; i < 6; i++) {
            result1 += random.nextInt(10);
        }
        String ordNo = System.nanoTime() + result1;
        JSONObject reqData = new JSONObject();
        reqData.put("mno", dept.getMno());
        reqData.put("ordNo", ordNo);
        reqData.put("origOrderNo", payOrder.getOrderNo());
        reqData.put("amt", payOrder.getAmt());
        reqData.put("origUuid", "");
        reqData.put("origSxfUuid", "");
        String req = SXFPaySign.getSXFPay(reqData);
        ///logger.debug("参数信息："+req);
        System.out.println("req:" + req);
        //此处不要改变reqData里面值的顺序用LinkedHashMap
        HashMap reqMap = JSON.parseObject(req, LinkedHashMap.class, Feature.OrderedField);
        //组装加密串
        String signContent = RSASignature.getOrderContent(reqMap);
        System.out.println("拼接后的参数：" + signContent);
        //logger.debug("拼接后的参数："+signContent);
        //sign
        String sign = RSASignature.encryptBASE64(RSASignature.sign(signContent, SXFPaySign.privateKey));
        System.out.println("============签名:" + sign);
        reqMap.put("sign", sign);
        String reqStr = JSON.toJSONString(reqMap);
        System.out.println("请求参数:" + reqMap);
        System.out.println("请求参数:" + reqStr);
        //调用第三方接口地址
        String url = "https://openapi.suixingpay.com/merchant/order/refund";//生产地址
        String resultJson = HttpUtils.connectPostUrl(url, reqStr);
        System.out.println("返回信息：" + resultJson);
        //不要对reqData排序 所以用LinkedHashMap
        HashMap<String, Object> result = JSON.parseObject(resultJson, LinkedHashMap.class, Feature.OrderedField);
        if ("0000".equals(result.get("code"))) {
            //验签
            String signResult = result.get("sign").toString();
            result.remove("sign");
            String resultStr = RSASignature.getOrderContent(result);
            System.out.println("resultStr: " + resultStr);
            //sign
            String resultSign = RSASignature.encryptBASE64(RSASignature.sign(signContent, SXFPaySign.privateKey));
            System.out.println("resultSign: " + resultSign);
            //组装加密串
            if (RSASignature.doCheck(resultStr, signResult, SXFPaySign.sxfPublic)) {
                System.out.println("===================验签成功==============");
                //
                if (result.containsKey("respData")) {
                    HashMap<String, Object> result2 = JSON.parseObject(result.get("respData") + "", LinkedHashMap.class, Feature.OrderedField);
                    if ("0000".equals(result2.get("bizCode"))) {
                        respon.setResponCode("0000");
                        System.out.println(result2.get("retUrl"));
                        String url1 = result2.get("retUrl") + "";
                        respon.setResponMessage(result2.get("retUrl") + "");
                        return respon;
                    } else {
                        respon.setResponCode(result2.get("bizCode") + "");
                        respon.setResponMessage(result2.get("bizMsg") + "");
                    }
                    //判断 bizCode bizCode =="0000" 则业务成功
                } else {
                    respon.setResponCode("0004");
                    respon.setResponMessage(result.get("msg") + "");
                }
            } else {
                respon.setResponCode("0002");
                respon.setResponMessage("RSA验证失败");
            }
        }
        return respon;
    }

    /***
     *
     *查询交易流水
     *
     *
     * */

    public SysRespon sxfStructureClass(PayOrder payOrder) throws Exception {

        SysRespon respon = new SysRespon();
        SysDept dept = deptService.selectDeptById(payOrder.getStationId());
        Random random = new Random();
        String result1 = "";
        for (int i = 0; i < 6; i++) {
            result1 += random.nextInt(10);
        }
        String ordNo = System.nanoTime() + result1;
        JSONObject reqData = new JSONObject();
        reqData.put("mno", "399211110962855");
        reqData.put("queryTime", "20211118");
        String req = SXFPaySign.getSXFPay(reqData);
        ///logger.debug("参数信息："+req);
        System.out.println("req:" + req);
        //此处不要改变reqData里面值的顺序用LinkedHashMap
        HashMap reqMap = JSON.parseObject(req, LinkedHashMap.class, Feature.OrderedField);
        //组装加密串
        String signContent = RSASignature.getOrderContent(reqMap);
        System.out.println("拼接后的参数：" + signContent);
        //logger.debug("拼接后的参数："+signContent);
        //sign
        String sign = RSASignature.encryptBASE64(RSASignature.sign(signContent, SXFPaySign.privateKey));
        System.out.println("============签名:" + sign);
        reqMap.put("sign", sign);
        String reqStr = JSON.toJSONString(reqMap);
        System.out.println("请求参数:" + reqMap);
        System.out.println("请求参数:" + reqStr);
        //调用第三方接口地址
        String url = "https://openapi.suixingpay.com/capital/query/querySettlement";//生产地址
        String resultJson = HttpUtils.connectPostUrl(url, reqStr);
        System.out.println("返回信息：" + resultJson);
        //不要对reqData排序 所以用LinkedHashMap
        HashMap<String, Object> result = JSON.parseObject(resultJson, LinkedHashMap.class, Feature.OrderedField);
        if ("0000".equals(result.get("code"))) {
            //验签
            String signResult = result.get("sign").toString();
            result.remove("sign");
            String resultStr = RSASignature.getOrderContent(result);
            System.out.println("resultStr: " + resultStr);
            //sign
            String resultSign = RSASignature.encryptBASE64(RSASignature.sign(signContent, SXFPaySign.privateKey));
            System.out.println("resultSign: " + resultSign);
            //组装加密串
            if (RSASignature.doCheck(resultStr, signResult, SXFPaySign.sxfPublic)) {
                System.out.println("===================验签成功==============");
                //
                if (result.containsKey("respData")) {
                    HashMap<String, Object> result2 = JSON.parseObject(result.get("respData") + "", LinkedHashMap.class, Feature.OrderedField);
                    if ("0000".equals(result2.get("bizCode"))) {
                        respon.setResponCode("0000");
                        System.out.println(result2.get("retUrl"));
                        String url1 = result2.get("retUrl") + "";
                        respon.setResponMessage(result2.get("retUrl") + "");
                        return respon;
                    } else {
                        respon.setResponCode(result2.get("bizCode") + "");
                        respon.setResponMessage(result2.get("bizMsg") + "");
                    }
                    //判断 bizCode bizCode =="0000" 则业务成功
                } else {
                    respon.setResponCode("0004");
                    respon.setResponMessage(result.get("msg") + "");
                }
            } else {
                respon.setResponCode("0002");
                respon.setResponMessage("RSA验证失败");
            }
        }
        return respon;
    }

    /**
     * 恢复正常付款状态
     */
    @GetMapping(value = "/reback/{orderId}")
    public AjaxResult reback(@PathVariable("orderId") Long orderId) {
        int i = 0;
        PayOrder payOrder = new PayOrder();
        PayOrder payOrder1 = payOrderService.selectPayOrderById(orderId);
        if (payOrder1.getStatus().equals("1")) {
            return AjaxResult.error("已经支付成功，不能重新回退");
        }
        StationBalanceChange stationBalanceChange = new StationBalanceChange();
        LoginUser currentUser = SecurityUtils.getLoginUser();
        stationBalanceChange.setAmt(payOrder1.getAmt());
        stationBalanceChange.setStationId(payOrder1.getStationId());
        stationBalanceChange.setType("-");
        stationBalanceChange.setCreateBy(currentUser.getUser().getUserId() + "");
        Long deptId = payOrder1.getStationId();
        SysDept dept1 = deptService.selectDeptById(deptId);
        SysDept dept = new SysDept();
        Float Balance1 = Float.parseFloat(dept1.getBalance().toString());
        Float value = Float.parseFloat(payOrder1.getAmt().toString());
        stationBalanceChange.setNowAmt(dept1.getBalance());
        dept.setDeptId(deptId);
        dept.setBalance(BigDecimal.valueOf(Balance1 - value));
        i = deptService.updateDept(dept);
        if (i != 0) {
            payOrder.setOrderId(orderId);
            payOrder.setStatus("1");//设置为已退款
            stationBalanceChangeService.insertStationBalanceChange(stationBalanceChange);
            i = payOrderService.updatePayOrder(payOrder);
        }
        if (i == 0) {
            return AjaxResult.error();
        }
        return AjaxResult.success(i);
    }

    /**
     * 获取92号汽油数据
     *
     * @param payOrder
     * @return
     */
    @GetMapping("/listQydata92")
    public TableDataInfo listQydata92(PayOrder payOrder) {
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            if(CollectionUtil.isEmpty(stations)){
                return getTable(new ArrayList<>());
            }
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }


        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else {
            Station station = new Station();
            List<Station> stations = stationService.selectStationList(station);
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }

        }
        payOrder.setOilName("92#");
        payOrder.setStatus("1");
        //payOrder.setOrderType("1");
        List<PayOrder> orderList = payOrderService.listQydata(payOrder);
        return getTable(orderList);
    }

    /**
     * 获取95号汽油数据
     *
     * @param payOrder
     * @return
     */
    @GetMapping("/listQydata95")
    public TableDataInfo listQydata95(PayOrder payOrder) {
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            if(CollectionUtil.isEmpty(stations)){
                return getTable(new ArrayList<>());
            }
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }


        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else {
            Station station = new Station();
            List<Station> stations = stationService.selectStationList(station);
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }

        }
        payOrder.setOilName("95#");
        //payOrder.setStatus("1");
        //payOrder.setOrderType("1");
        List<PayOrder> orderList = payOrderService.listQydata(payOrder);
        return getTable(orderList);
    }

    /**
     * 获取97号汽油数据
     *
     * @param payOrder
     * @return
     */
    @GetMapping("/listQydata98")
    public TableDataInfo listQydata98(PayOrder payOrder) {
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            if(CollectionUtil.isEmpty(stations)){
                return getTable(new ArrayList<>());
            }
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }


        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else {
            Station station = new Station();
            List<Station> stations = stationService.selectStationList(station);
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }

        }
        payOrder.setOilName("98#");
        //payOrder.setStatus("1");
        //payOrder.setOrderType("1");
        List<PayOrder> orderList = payOrderService.listQydata(payOrder);
        return getTable(orderList);
    }

    /**
     * 获取97号汽油数据
     *
     * @param payOrder
     * @return
     */
    @GetMapping("/listQydata20")
    public TableDataInfo listQydata20(PayOrder payOrder) {
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            if(CollectionUtil.isEmpty(stations)){
                return getTable(new ArrayList<>());
            }
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }

        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else {
            Station station = new Station();
            List<Station> stations = stationService.selectStationList(station);
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }

        }
        payOrder.setOilName("-20#");
        //payOrder.setStatus("1");
        //payOrder.setOrderType("1");
        List<PayOrder> orderList = payOrderService.listQydata(payOrder);
        return getTable(orderList);
    }

    /**
     * 获取97号汽油数据
     *
     * @param payOrder
     * @return
     */
    @GetMapping("/listQydata0")
    public TableDataInfo listQydata0(PayOrder payOrder) {
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            if(CollectionUtil.isEmpty(stations)){
                return getTable(new ArrayList<>());
            }
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }


        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else {

        }
        payOrder.setOilName("0#");
        //payOrder.setStatus("1");
        //payOrder.setOrderType("1");
        List<PayOrder> orderList = payOrderService.listQydata(payOrder);
        return getTable(orderList);
    }

    /**
     * 获取97号汽油数据
     *
     * @param payOrder
     * @return
     */
    @GetMapping("/listQydata10")
    public TableDataInfo listQydata10(PayOrder payOrder) {
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            if(CollectionUtil.isEmpty(stations)){
                return getTable(new ArrayList<>());
            }
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }


        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else {

        }
        payOrder.setOilName("-10#");
        //payOrder.setStatus("1");
        //payOrder.setOrderType("1");
        List<PayOrder> orderList = payOrderService.listQydata(payOrder);
        return getTable(orderList);
    }

    /**
     * 获取x轴数据
     *
     * @param payOrder
     * @return
     */
    @GetMapping("/listXdata")
    public TableDataInfo listXdata(PayOrder payOrder) {
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            if(CollectionUtil.isEmpty(stations)){
                return getTable(new ArrayList<>());
            }
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }


        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else {

        }
        //payOrder.setStatus("1");
        //payOrder.setOrderType("1");
        List<PayOrder> orderList = payOrderService.listXdata(payOrder);
        return getTable(orderList);
    }

    /**
     * 查询油站第一笔订单的数据
     */
    @GetMapping("/getPayOrderInfoMin")
    public AjaxResult getPayOrderInfoMin(PayOrder payOrder) {
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            if(CollectionUtil.isEmpty(stations)){
                return AjaxResult.success(new PayOrder());
            }
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }


        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else {

        }
        //payOrder.setStatus("1");
        //payOrder.setOrderType("1");
        return AjaxResult.success(payOrderService.getPayOrderInfoMin(payOrder));
    }

    /**
     * 新增订单支付
     */
    @Log(title = "订单支付", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PayOrder payOrder) {
        return toAjax(payOrderService.insertPayOrder(payOrder));
    }

    /**
     * 修改订单支付
     */
    @Log(title = "订单支付", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PayOrder payOrder) {
        return toAjax(payOrderService.updatePayOrder(payOrder));
    }

    /**
     * 删除订单支付
     */
    @Log(title = "订单支付", businessType = BusinessType.DELETE)
    @DeleteMapping("/{orderIds}")
    public AjaxResult remove(@PathVariable Long[] orderIds) {
        return toAjax(payOrderService.deletePayOrderByIds(orderIds));
    }

    /**
     * 查询订单支付列表
     */
    @GetMapping("/LNGDeptList")
    public TableDataInfo LNGDeptList(PayOrder payOrder) {
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            if(CollectionUtil.isEmpty(stations)){
                return getDataTable(new ArrayList<>());
            }
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }


        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else {

        }
        startPage();
        payOrder.setStatus("1");
        List<PayOrder> payOrderList = payOrderService.LNGDeptList(payOrder);
        return getDataTable(payOrderList);
    }

    /**
     * 查询订单支付列表
     */
    @GetMapping("/LNGlist")
    public TableDataInfo LNGlist(PayOrder payOrder) {
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            if(CollectionUtil.isEmpty(stations)){
                return getDataTable(new ArrayList<>());
            }
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }


        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }

        }
        startPage();
        payOrder.setStatus("1");
        List<PayOrder> payOrderList = payOrderService.selectLNGPayOrderExport(payOrder);
        return getDataTable(payOrderList);
    }

    @Log(title = "导出LNG", businessType = BusinessType.EXPORT)
    @GetMapping("/LNGExport")
    public AjaxResult LNGExport(PayOrder payOrder) {
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            if(CollectionUtil.isEmpty(stations)){
                return AjaxResult.error("未来查询到油站信息");
            }
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }


        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }

        }
        payOrder.setStatus("1");
        List<PayOrder> payOrderList = payOrderService.selectLNGPayOrderExport(payOrder);
        AjaxResult ss = exportExcel(payOrderList, "导出订单信息");
        return ss;
    }

    private AjaxResult exportExcel(List<PayOrder> payOrderList, String sheetName) {
        OutputStream out = null;
        Workbook wb = new SXSSFWorkbook(500);
        try {
            Sheet sheet = wb.createSheet(sheetName);
            sheet.setDefaultColumnWidth(20);//默认列宽20
            CellStyle style = wb.createCellStyle();
            CreationHelper createHelper = wb.getCreationHelper();
            style.setDataFormat(createHelper.createDataFormat().getFormat("yyyy-mm-dd hh:mm:ss"));
            int rows = payOrderList.size() + 1;
            Cell cell = null;
            Row row = null;
            for (int i = 0; i < rows; i++) {
                if (i == 0) {
                    row = sheet.createRow(i);
                    cell = row.createCell(0);
                    cell.setCellValue("油站名称");
                    cell.setCellStyle(style);
                    cell = row.createCell(1);
                    cell.setCellValue("油品");
                    cell.setCellStyle(style);
                    cell = row.createCell(2);
                    cell.setCellValue("订单号");
                    cell.setCellStyle(style);
                    cell = row.createCell(3);
                    cell.setCellValue("枪标价");
                    cell.setCellStyle(style);
                    cell = row.createCell(4);
                    cell.setCellValue("结算价");
                    cell.setCellStyle(style);
                    cell = row.createCell(5);
                    cell.setCellValue("司机价");
                    cell.setCellStyle(style);
                    cell = row.createCell(6);
                    cell.setCellValue("升数");
                    cell.setCellStyle(style);
                    cell = row.createCell(7);
                    cell.setCellValue("应付金额");
                    cell.setCellStyle(style);
                    cell = row.createCell(8);
                    cell.setCellValue("结算金额");
                    cell.setCellStyle(style);
                    cell = row.createCell(9);
                    cell.setCellValue("司机金额");
                    cell.setCellStyle(style);
                    cell = row.createCell(10);
                    cell.setCellValue("支付时间");
                    cell.setCellStyle(style);
                    cell = row.createCell(11);
                    cell.setCellValue("手机号");
                    cell.setCellStyle(style);
                } else {
                    row = sheet.createRow(i);
                    int j = i - 1;
                    cell = row.createCell(0);
                    cell.setCellValue(payOrderList.get(j).getStationName());
                    cell.setCellStyle(style);
                    cell = row.createCell(1);
                    cell.setCellValue(payOrderList.get(j).getOilName());
                    cell.setCellStyle(style);
                    cell = row.createCell(2);
                    cell.setCellValue(payOrderList.get(j).getOrderNo());
                    cell.setCellStyle(style);
                    cell = row.createCell(3);
                    cell.setCellValue(payOrderList.get(j).getOilPirce() + "");
                    cell.setCellStyle(style);
                    cell = row.createCell(4);
                    if (payOrderList.get(j).getSellOilPrice() != null) {
                        cell.setCellValue(payOrderList.get(j).getSellOilPrice() + "");
                    } else {
                        cell.setCellValue("0");
                    }
                    cell.setCellStyle(style);
                    cell = row.createCell(5);
                    if (payOrderList.get(j).getDriverOilPrice() != null) {
                        cell.setCellValue(payOrderList.get(j).getDriverOilPrice() + "");
                    } else {
                        cell.setCellValue("0");
                    }
                    cell.setCellStyle(style);
                    cell = row.createCell(6);
                    if (payOrderList.get(j).getOrderLiters() != null) {
                        cell.setCellValue(payOrderList.get(j).getOrderLiters() + "");
                    } else {
                        cell.setCellValue("0");
                    }
                    cell.setCellStyle(style);
                    cell = row.createCell(7);
                    if (payOrderList.get(j).getReceivableAmt() != null) {
                        cell.setCellValue(payOrderList.get(j).getReceivableAmt() + "");
                    } else {
                        cell.setCellValue("0");
                    }
                    cell.setCellStyle(style);
                    cell = row.createCell(8);
                    if (payOrderList.get(j).getSellAmt() != null) {
                        cell.setCellValue(payOrderList.get(j).getSellAmt() + "");
                    } else {
                        cell.setCellValue("0");
                    }
                    cell.setCellStyle(style);
                    cell = row.createCell(9);
                    if (payOrderList.get(j).getAmt() != null) {
                        cell.setCellValue(payOrderList.get(j).getAmt() + "");
                    } else {
                        cell.setCellValue("0");
                    }
                    cell.setCellStyle(style);
                    cell = row.createCell(10);
                    cell.setCellValue(payOrderList.get(j).getPayDate());
                    cell.setCellStyle(style);
                    cell = row.createCell(11);
                    cell.setCellValue(payOrderList.get(j).getMobilePhone());
                    cell.setCellStyle(style);
                }
            }
            String filename = encodingFilename(sheetName);
            out = new FileOutputStream(getAbsoluteFile(filename));
            wb.write(out);
            return AjaxResult.success(filename);
        } catch (Exception e) {
            log.error("导出Excel异常{}", e.getMessage());
            throw new CustomException("导出Excel失败，请联系网站管理员！");
        } finally {
            if (wb != null) {
                try {
                    wb.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

    private String encodingFilename(String filename) {
        filename = UUID.randomUUID().toString() + "_" + filename + ".xlsx";
        return filename;
    }

    public String getAbsoluteFile(String filename) {
        String downloadPath = QuJiaConfig.getDownloadPath() + filename;
        File desc = new File(downloadPath);
        if (!desc.getParentFile().exists()) {
            desc.getParentFile().mkdirs();
        }
        return downloadPath;
    }

    @Log(title = "导出LNG站点", businessType = BusinessType.EXPORT)
    @GetMapping("/LNGDeptExport")
    public AjaxResult LNGDeptExport(PayOrder payOrder) {
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            if(CollectionUtil.isEmpty(stations)){
                return AjaxResult.error("未来查询到油站信息");
            }
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }


        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else {

        }
        //payOrder.setStatus("1");
        List<PayOrder> payOrderList = payOrderService.LNGDeptList(payOrder);
        AjaxResult ss = exportDeptExcel(payOrderList, "导出订单信息");
        return ss;
    }

    private AjaxResult exportDeptExcel(List<PayOrder> payOrderList, String sheetName) {
        OutputStream out = null;
        Workbook wb = new SXSSFWorkbook(500);
        try {
            Sheet sheet = wb.createSheet(sheetName);
            sheet.setDefaultColumnWidth(20);//默认列宽20
            CellStyle style = wb.createCellStyle();
            CreationHelper createHelper = wb.getCreationHelper();
            style.setDataFormat(createHelper.createDataFormat().getFormat("yyyy-mm-dd hh:mm:ss"));
            int rows = payOrderList.size() + 1;
            Cell cell = null;
            Row row = null;
            for (int i = 0; i < rows; i++) {
                if (i == 0) {
                    row = sheet.createRow(i);
                    cell = row.createCell(0);
                    cell.setCellValue("油站名称");
                    cell.setCellStyle(style);
                    cell = row.createCell(1);
                    cell.setCellValue("订单号");
                    cell.setCellStyle(style);
                    cell = row.createCell(2);
                    cell.setCellValue("油品");
                    cell.setCellStyle(style);
                    cell = row.createCell(3);
                    cell.setCellValue("枪标价");
                    cell.setCellStyle(style);
                    cell = row.createCell(4);
                    cell.setCellValue("结算价");
                    cell.setCellStyle(style);
                    cell = row.createCell(5);
                    cell.setCellValue("升数");
                    cell.setCellStyle(style);
                    cell = row.createCell(6);
                    cell.setCellValue("应付金额");
                    cell.setCellStyle(style);
                    cell = row.createCell(7);
                    cell.setCellValue("结算金额");
                    cell.setCellStyle(style);
                    cell = row.createCell(8);
                    cell.setCellValue("结算优惠金额");
                    cell.setCellStyle(style);
                    cell = row.createCell(9);
                    cell.setCellValue("支付时间");
                    cell.setCellStyle(style);
                    cell = row.createCell(10);
                    cell.setCellValue("手机号");
                    cell.setCellStyle(style);
                } else {
                    row = sheet.createRow(i);
                    int j = i - 1;
                    cell = row.createCell(0);
                    cell.setCellValue(payOrderList.get(j).getStationName());
                    cell.setCellStyle(style);
                    cell = row.createCell(1);
                    cell.setCellValue(payOrderList.get(j).getOrderNo());
                    cell.setCellStyle(style);
                    cell = row.createCell(2);
                    cell.setCellValue(payOrderList.get(j).getOilName());
                    cell.setCellStyle(style);
                    cell = row.createCell(3);
                    cell.setCellValue(payOrderList.get(j).getOilPirce() + "");
                    cell.setCellStyle(style);
                    cell = row.createCell(4);
                    if (payOrderList.get(j).getSellOilPrice() != null) {
                        cell.setCellValue(payOrderList.get(j).getSellOilPrice() + "");
                    } else {
                        cell.setCellValue("0");
                    }
                    cell.setCellStyle(style);
                    cell = row.createCell(5);
                    cell.setCellValue(payOrderList.get(j).getOrderLiters() + "");
                    cell.setCellStyle(style);
                    cell = row.createCell(6);
                    if (payOrderList.get(j).getReceivableAmt() != null) {
                        cell.setCellValue(payOrderList.get(j).getReceivableAmt() + "");
                    } else {
                        cell.setCellValue("0");
                    }
                    cell.setCellStyle(style);
                    cell = row.createCell(7);
                    if (payOrderList.get(j).getSellAmt() != null) {
                        cell.setCellValue(payOrderList.get(j).getSellAmt() + "");
                    } else {
                        cell.setCellValue("0");
                    }
                    cell.setCellStyle(style);
                    cell = row.createCell(8);
                    if (payOrderList.get(j).getSellDiscountAmt() != null) {
                        cell.setCellValue(payOrderList.get(j).getSellDiscountAmt() + "");
                    } else {
                        cell.setCellValue("0");
                    }
                    cell.setCellStyle(style);
                    cell = row.createCell(9);
                    cell.setCellValue(payOrderList.get(j).getPayDate());
                    cell.setCellStyle(style);
                    cell = row.createCell(10);
                    cell.setCellValue(payOrderList.get(j).getMobilePhone());
                    cell.setCellStyle(style);
                }
            }
            String filename = encodingFilename(sheetName);
            out = new FileOutputStream(getAbsoluteFile(filename));
            wb.write(out);
            return AjaxResult.success(filename);
        } catch (Exception e) {
            log.error("导出Excel异常{}", e.getMessage());
            throw new CustomException("导出Excel失败，请联系网站管理员！");
        } finally {
            if (wb != null) {
                try {
                    wb.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

    /**
     * 补打订单信息
     */
    @Log(title = "补打订单小票", businessType = BusinessType.OTHER)
    @GetMapping("/printOrderInfo")
    public AjaxResult printOrderInfo(PayOrder payOrder) {
        int i = 0;
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (payOrder.getOrderId() != null) {
            String content1 = "";
            String content2 = "";
            PayOrder order = payOrderService.selectPayOrderById(payOrder.getOrderId());
            if (order != null) {
                String paytype = "";
                String phoneNumber = "";
                if (order.getCustomerPhone() != null) {
                    phoneNumber = order.getCustomerPhone().replaceAll("(\\w{3})\\w*(\\w{4})", "$1****$2");
                }
                if (order.getPayType().equals("wx")) {
                    paytype = "微信";
                } else if (order.getPayType().equals("dzk")) {
                    paytype = "电子卡";
                } else if (order.getPayType().equals("zfb")) {
                    paytype = "支付宝";
                } else if (order.getPayType().equals("xj")) {
                    paytype = "现金";
                }
                content1 = "<CB>油品订单--顾客联</CB><BR>";
                content1 += "<BR>";
                content1 += "--------------------------------<BR>";
                content1 += "<BR>";
                content1 += "<BOLD><B>原价： " + order.getReceivableAmt() + " 元</B></BOLD><BR>";
                content1 += "订单号：" + order.getOrderNo() + " <BR>";
                content1 += "支付方式： " + paytype + " <BR>";
                content1 += "下单时间：" + dateFormat.format(order.getCreatedDate()) + " <BR>";
                content1 += "付款时间：" + dateFormat.format(order.getPayDate()) + " <BR>";
                content1 += "油站：" + order.getStationName() + "  <BR>";
                content1 += "油枪：" + order.getOilGun() + "号枪<BR>";
                if (order.getOilType() != null && !order.getOilType().equals("3")) {
                    content1 += "油品： " + order.getOilName() + "  <BR>";
                    content1 += "油量： " + order.getOrderLiters() + "  升<BR>";
                    content1 += "单价： " + order.getOilPirce() + " L/元<BR>";
                    content1 += "优惠： " + order.getDiscountAmt() + " 元<BR>";
                }
                content1 += "支付： " + order.getAmt() + " 元<BR>";
                content1 += "手机号： " + phoneNumber + " <BR>";
                content1 += "加油员： " + order.getOilPersonnel() + " <BR>";
                content1 += "<BR>";

                content2 = "<CB>油品订单--商户联</CB><BR>";
                content2 += "<BR>";
                content2 += "--------------------------------<BR>";
                content2 += "<BR>";
                content2 += "<BOLD><B>原价： " + order.getReceivableAmt() + " 元</B></BOLD><BR>";
                content2 += "订单号：" + order.getOrderNo() + "  <BR>";
                content2 += "支付方式： " + paytype + " <BR>";
                content2 += "下单时间：" + dateFormat.format(order.getCreatedDate()) + " <BR>";
                content2 += "付款时间：" + dateFormat.format(order.getPayDate()) + " <BR>";
                content2 += "油站：" + order.getStationName() + "  <BR>";
                content2 += "油枪：" + order.getOilGun() + "号枪<BR>";
                if (order.getOilType() != null && !order.getOilType().equals("3")) {
                    content2 += "油品： " + order.getOilName() + "  <BR>";
                    content2 += "油量： " + order.getOrderLiters() + "  升<BR>";
                    content2 += "单价： " + order.getOilPirce() + " L/元<BR>";
                    content2 += "优惠： " + order.getDiscountAmt() + " 元<BR>";
                }
                content2 += "支付： " + order.getAmt() + " 元<BR>";
                content2 += "手机号： " + phoneNumber + " <BR>";
                content2 += "<BR>";
            }
            Map params = new HashMap();
            params.put("stationId", order.getStationId());
            params.put("deviceType", "1");
            Map mp = stationDeviceManageService.getPrinterSnByStationId(params);
            SysDept dept = deptService.selectDeptById(order.getStationId());
            if (mp != null && mp.containsKey("device_no") && mp.get("device_no") != null && mp.get("device_no") != "") {
                String sn = mp.get("device_no").toString();
                if (dept != null && dept.getPrintSetting() != null && dept.getPrintSetting().equals("1") && content1 != null) {
                    FeiEPrinterUtil.printReceipt(sn, content1);
                    i = 1;
                    logger.info("客户联打印成功");
                } else if (dept != null && dept.getPrintSetting() != null && dept.getPrintSetting().equals("2") && content2 != null) {
                    FeiEPrinterUtil.printReceipt(sn, content2);
                    i = 1;
                    logger.info("商户联打印成功");
                } else if (dept != null && dept.getPrintSetting() != null && dept.getPrintSetting().equals("3") && content1 != null && content2 != null) {
                    FeiEPrinterUtil.printReceipt(sn, content1 + content2);
                    i = 1;
                    logger.info("客户联和商户联打印成功");
                } else {
                    i = 0;
                    logger.info("打印失败");
                }
            } else {
                logger.info("请正确配置打印机");
                i = 2;
            }
        }
        return toAjaxee(i);
    }


    /**
     * 补打订单信息
     */
    @Log(title = "外部上传订单", businessType = BusinessType.OTHER)
    @GetMapping("/addPayOrder")
    public AjaxResult addPayOrder(PayOrder payOrder) {
        int i = 0;
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (payOrder.getOrderId() != null) {
            String content1 = "";
            String content2 = "";
            PayOrder order = payOrderService.selectPayOrderById(payOrder.getOrderId());
            if (order != null) {
                String paytype = "";
                String phoneNumber = "";
                if (order.getCustomerPhone() != null) {
                    phoneNumber = order.getCustomerPhone().replaceAll("(\\w{3})\\w*(\\w{4})", "$1****$2");
                }
                if (order.getPayType().equals("wx")) {
                    paytype = "微信";
                } else if (order.getPayType().equals("dzk")) {
                    paytype = "电子卡";
                } else if (order.getPayType().equals("zfb")) {
                    paytype = "支付宝";
                } else if (order.getPayType().equals("xj")) {
                    paytype = "现金";
                }
                content1 = "<CB>油品订单--顾客联</CB><BR>";
                content1 += "<BR>";
                content1 += "--------------------------------<BR>";
                content1 += "<BR>";
                content1 += "<BOLD><B>原价： " + order.getReceivableAmt() + " 元</B></BOLD><BR>";
                content1 += "订单号：" + order.getOrderNo() + " <BR>";
                content1 += "支付方式： " + paytype + " <BR>";
                content1 += "下单时间：" + dateFormat.format(order.getCreatedDate()) + " <BR>";
                content1 += "付款时间：" + dateFormat.format(order.getPayDate()) + " <BR>";
                content1 += "油站：" + order.getStationName() + "  <BR>";
                content1 += "油枪：" + order.getOilGun() + "号枪<BR>";
                if (order.getOilType() != null && !order.getOilType().equals("3")) {
                    content1 += "油品： " + order.getOilName() + "  <BR>";
                    content1 += "油量： " + order.getOrderLiters() + "  升<BR>";
                    content1 += "单价： " + order.getOilPirce() + " L/元<BR>";
                    content1 += "优惠： " + order.getDiscountAmt() + " 元<BR>";
                }
                content1 += "支付： " + order.getAmt() + " 元<BR>";
                content1 += "手机号： " + phoneNumber + " <BR>";
                content1 += "加油员： " + order.getOilPersonnel() + " <BR>";
                content1 += "<BR>";

                content2 = "<CB>油品订单--商户联</CB><BR>";
                content2 += "<BR>";
                content2 += "--------------------------------<BR>";
                content2 += "<BR>";
                content2 += "<BOLD><B>原价： " + order.getReceivableAmt() + " 元</B></BOLD><BR>";
                content2 += "订单号：" + order.getOrderNo() + "  <BR>";
                content2 += "支付方式： " + paytype + " <BR>";
                content2 += "下单时间：" + dateFormat.format(order.getCreatedDate()) + " <BR>";
                content2 += "付款时间：" + dateFormat.format(order.getPayDate()) + " <BR>";
                content2 += "油站：" + order.getStationName() + "  <BR>";
                content2 += "油枪：" + order.getOilGun() + "号枪<BR>";
                if (order.getOilType() != null && !order.getOilType().equals("3")) {
                    content2 += "油品： " + order.getOilName() + "  <BR>";
                    content2 += "油量： " + order.getOrderLiters() + "  升<BR>";
                    content2 += "单价： " + order.getOilPirce() + " L/元<BR>";
                    content2 += "优惠： " + order.getDiscountAmt() + " 元<BR>";
                }
                content2 += "支付： " + order.getAmt() + " 元<BR>";
                content2 += "手机号： " + phoneNumber + " <BR>";
                content2 += "<BR>";
            }
            Map params = new HashMap();
            params.put("stationId", order.getStationId());
            params.put("deviceType", "1");
            Map mp = stationDeviceManageService.getPrinterSnByStationId(params);
            SysDept dept = deptService.selectDeptById(order.getStationId());
            if (mp != null && mp.containsKey("device_no") && mp.get("device_no") != null && mp.get("device_no") != "") {
                String sn = mp.get("device_no").toString();
                if (dept != null && dept.getPrintSetting() != null && dept.getPrintSetting().equals("1") && content1 != null) {
                    FeiEPrinterUtil.printReceipt(sn, content1);
                    i = 1;
                    logger.info("客户联打印成功");
                } else if (dept != null && dept.getPrintSetting() != null && dept.getPrintSetting().equals("2") && content2 != null) {
                    FeiEPrinterUtil.printReceipt(sn, content2);
                    i = 1;
                    logger.info("商户联打印成功");
                } else if (dept != null && dept.getPrintSetting() != null && dept.getPrintSetting().equals("3") && content1 != null && content2 != null) {
                    FeiEPrinterUtil.printReceipt(sn, content1 + content2);
                    i = 1;
                    logger.info("客户联和商户联打印成功");
                } else {
                    i = 0;
                    logger.info("打印失败");
                }
            } else {
                logger.info("请正确配置打印机");
                i = 2;
            }
        }
        return toAjaxee(i);
    }

    @GetMapping("/selectOrderStatus")
    public AjaxResult selectOrderStatus(PayOrder payOrder) {


        return AjaxResult.success(payOrderService.selectOrderStatus(payOrder));
    }

    @ApiOperation(value = "获取员工码订单统计分页列表", notes = "获取员工码订单统计")
    @GetMapping("/payOrderEmployee")
    public TableDataInfo payOrderEmployeePage(PayOrderEmployeeQueryForm payOrderEmployeeQueryForm) {
        if (Objects.isNull(payOrderEmployeeQueryForm) || StringUtils.isBlank(payOrderEmployeeQueryForm.getBeginTime())
                || StringUtils.isBlank(payOrderEmployeeQueryForm.getEndTime())) {
            TableDataInfo rspData = new TableDataInfo();
            rspData.setCode(HttpStatus.ERROR);
            rspData.setMsg("查询时间不能为空");
            rspData.setRows(null);
            rspData.setTotal(0);
        }
        SysUser user = SecurityUtils.getLoginUser().getUser();
        String userLevel = user.getUserLevel();
//        if (StringUtils.isNotEmpty(userLevel) && userLevel.equals("1")) // 1:油企
//            payOrderEmployeeQueryForm.setEnterpriseId(user.getEnterpriseId());
//        if (StringUtils.isNotEmpty(userLevel) && userLevel.equals("2")) // 2:油站
//            payOrderEmployeeQueryForm.setOilPersonnelId(user.getUserId());
        if (StringUtils.equals(UserConstants.LEVEL_TWO, userLevel)) {  //油企
            payOrderEmployeeQueryForm.setEnterpriseId(user.getEnterpriseId());
        } else if (StringUtils.equals(UserConstants.LEVEL_THREE, userLevel)) {  //油站
            if (StaffUtil.isStaff(user)) {
                payOrderEmployeeQueryForm.setOilPersonnelId(user.getUserId());
            } else {
                payOrderEmployeeQueryForm.setStationId(user.getStationId());
            }
        } else if (SecurityUtils.isPartner()) {
            EnterpriseAndStationVo itemIds = stationService.getItemIds(user);
            if(itemIds.getStationIds()!=null && itemIds.getStationIds().size() > 0) {
                payOrderEmployeeQueryForm.setStationIds(itemIds.getStationIds());
            }else {
                throw new CustomException("未创建油企");
            }
        }
        startPage();

        List<PayOrderEmployeeQueryVo> payOrderEmployeeQueryVoList = payOrderService.payOrderEmployeeList(payOrderEmployeeQueryForm);
        return getNullDataTable(payOrderEmployeeQueryVoList);
    }

    @ApiOperation(value = "员工收款明细", notes = "员工收款明细")
    @GetMapping("/payOrderEmployee/statistics")
    public AjaxResult payOrderEmployeePageStatistics(PayOrderEmployeeQueryForm payOrderEmployeeQueryForm) {
        PayOrderEmployeeQueryVo payOrderEmployeeQueryVo = payOrderService.payOrderEmployeeStatistics(payOrderEmployeeQueryForm);
        return AjaxResult.success(payOrderEmployeeQueryVo);
    }

    @ApiOperation(value = "根据员工id获取订单统计分页列表", notes = "获取订单统计分页列表")
    @GetMapping("/payOrderDetail")
    public TableDataInfo payOrderDetailPage(PayOrderDetailQueryForm payOrderDetailQueryForm) {
        startPage();
        List<PayOrderDetailQueryVo> payOrderEmployeeQueryVoList = payOrderService.payOrderDetailList(payOrderDetailQueryForm);
        return getNullDataTable(payOrderEmployeeQueryVoList);
    }


    //    @RequestMapping(value = "/JKNotice", consumes = "application/json", method = RequestMethod.POST)
//    public void JKNotice(HttpServletRequest request, HttpServletResponse response) {
//        // 接受异步消息
//        try {
//            String data = JKPayUtil.getParamByStream(request);
//            JSONObject obj = JSON.parseObject(data);
//            System.out.println("金控开始回调=" + obj);
//            obj.put("orderInfo", obj.getString("orderInfo").replaceAll(" ", "+"));
//            obj.put("signValue", obj.getString("signValue").replaceAll(" ", "+"));
//
//
//            String signvalue = obj.getString("signValue");
//            obj.remove("signValue");
//            Map verifyMap = (Map) JSONObject.parse(obj.toString());
//            String verifyContent = ParaUtils.createLinkString(ParaUtils.paraFilter(verifyMap));
//            boolean checkverify = CfcaCertUtil.verifyValue(verifyContent, signvalue, public_certPath);
//            if (checkverify) { //验签成功
//                String orderInfo = Base64Util.decodeString(obj.get("orderInfo") + "");
//                JSONObject orderInfoMessage = JSON.parseObject(orderInfo);
//                logger.info(orderInfo);
//                System.out.println("金控回调订单信息=" + orderInfo);
//                if (!"02".equals(orderInfoMessage.get("orderStatus")+"")) {
//                    logger.info("订单处理失败:"+orderInfoMessage.get("resultDesc"));
//                    throw new  Exception("支付失败："+orderInfoMessage.get("resultDesc"));
//                }
//                //通过金控订单号，定位订单
//                PayOrder payOrderInfo = payOrderService.selectOrderInfoByMerchantsNumber(orderInfoMessage.get("mfhcdOrderNo") + "");
//                if (payOrderInfo == null) {
//                    throw new Exception("订单不存在");
//                }
//                if (!"0".equals(payOrderInfo.getStatus())) {
//                    logger.info("getStatus" + payOrderInfo.getStatus());
//                    throw new Exception("订单状态不对");
//                }
//                payOrderInfo.setStatus("3");
//                payOrderInfo.setExaminStatus("2");
//                //修改订单状态
//                int count = payOrderService.updatePayOrder(payOrderInfo);
//
//                if (count != 1) {
//                    throw new Exception("订单修改失败");
//                }
//
//                response.getWriter().print("000000");
//            }
//        } catch (Exception e) {
//
//            logger.info("金控回调错误日志+" + e.getMessage());
//            e.printStackTrace();
//        }
//
//    }
    @ApiOperation(value = "获取订单开票记录")
    @GetMapping("/getInvoiceRecords")
    @ResponseBody
    public List<InvoiceInfoVo> getInvoiceRecords(String OrderNo, @RequestParam String businessName) {
        if (StringUtils.isEmpty(businessName)) {
            throw new CustomException("businessName不能为空");
        }
        if (StringUtils.isEmpty(OrderNo)) {
            return new ArrayList<InvoiceInfoVo>();
        }
        return invoiceService.getInvoiceRecords(OrderNo, businessName);
    }

    //去开票
    @ApiOperation(value = "去开票", httpMethod = "POST", notes = "开发票")
    @PostMapping("/goToInvoice")
    @ResponseBody
    @Transactional
    public String goToInvoice(@RequestBody GoToInvoice invoice) {
        String url = payBaseUrl + "/goToInvoice";
        String result = "";
        Gson gson = new Gson();
        try {
            result = HttpUtils.connectPostUrl(url, gson.toJson(invoice));
        } catch (Exception e) {
            return gson.toJson(AjaxResult.error(e.getMessage()));
        }
        return result;
    }

    public PayOrder assignPayOrder(PayOrder payOrder, SysUser user) {
        List<String> list = new ArrayList<>();
        if (UserConstants.LEVEL_ONE.equals(user.getUserLevel()) || StringUtils.isBlank(user.getUserLevel())) {
            if (StringUtils.isNotBlank(payOrder.getDistrictIds())) {
                Station station = new Station();

                List<Integer> districtIds = Arrays.stream(payOrder.getDistrictIds().split(",")).map(Integer::parseInt).collect(Collectors.toList());

                for (Integer district : districtIds) {

                    String districtName = getDistrict(district);


                    log.info("输入的地区,{}", districtName);
                    List<Long> enterpriseByDistrict = teamManagementService.getEnterpriseByDistrict(districtName);
                    log.info("获得该地区的所有油企id：{}", enterpriseByDistrict);
                    if (CollectionUtil.isNotEmpty(enterpriseByDistrict)) {
                        for (Long id : enterpriseByDistrict) {
                            station.setEnterpriseId(id);
                            List<Station> stations = stationService.selectStationList(station);
                            for (Station ss : stations) {
                                list.add(ss.getStationId() + "");
                            }
                            if (stations != null && stations.size() > 0) {
                                payOrder.setStationIdList(list);
                            }
                        }
                    } else {
                        //不存在则赋个没有值的油站
                        list.add("0");
                        payOrder.setStationIdList(list);
                    }
                }
            }
        } else if (UserConstants.LEVEL_FIVE.equals(user.getUserLevel())) {
            if (CollectionUtils.isEmpty(payOrder.getStationIdList()) && CollectionUtil.isEmpty(payOrder.getEnterpriseIdList())) {
                Station station = new Station();
                log.info("输入的负责人id：{}", user.getUserId());
                List<Long> managerEnterpriseId = teamManagementService.getManagerEnterpriseId(user.getUserId());
                log.info("该负责人id:{} , 所管理的油企id：{}", user.getUserId(), managerEnterpriseId);
                if (CollectionUtil.isNotEmpty(managerEnterpriseId)) {
                    for (Long id : managerEnterpriseId) {
                        station.setEnterpriseId(id);
                        List<Station> stations = stationService.selectStationList(station);
                        for (Station ss : stations) {
                            list.add(ss.getStationId() + "");
                        }
                        if (stations != null && stations.size() > 0) {
                            payOrder.setStationIdList(list);
                        }
                    }
                } else {
                    //不存在则赋个没有值的油站
                    list.add("0");
                    payOrder.setStationIdList(list);
                }

            }
        } else if (UserConstants.LEVEL_SIX.equals(user.getUserLevel())) {
            if (CollectionUtils.isEmpty(payOrder.getStationIdList()) && CollectionUtil.isEmpty(payOrder.getEnterpriseIdList())) {
                Station station = new Station();
                log.info("输入的业务员id：{}", user.getUserId());
                List<Long> managerEnterpriseId = memberManagementService.getMemberEnterpriseId(user.getUserId());
                log.info("该业务员id:{} , 所管理的油企id：{}", user.getUserId(), managerEnterpriseId);
                if (CollectionUtil.isNotEmpty(managerEnterpriseId)) {
                    for (Long id : managerEnterpriseId) {
                        station.setEnterpriseId(id);
                        List<Station> stations = stationService.selectStationList(station);
                        for (Station ss : stations) {
                            list.add(ss.getStationId() + "");
                        }
                        if (stations != null && stations.size() > 0) {
                            payOrder.setStationIdList(list);
                        }
                    }
                } else {
                    list.add("0");
                    payOrder.setStationIdList(list);
                }
            }
        }
        return payOrder;
    }

    /**
     * 获取员工最后一次班结时间 和 员工标识
     */
    @GetMapping("/employeePermission")
    @ApiOperation(value = "获取员工最后一次班结时间 和 员工标识")
    public AjaxResult getEmployeePermission() {
        EmployeePermissionVo employeePermissionVo = new EmployeePermissionVo();
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if (Objects.isNull(user)) {
            List<String> range = new ArrayList<>();
            range.add(DateUtils.dateTime(new Date()));
            range.add(DateUtils.dateTime(new Date()));
            employeePermissionVo.setRange(range);
            employeePermissionVo.setStaff(Boolean.FALSE);
            employeePermissionVo.setEmployeeShow("0");
            return AjaxResult.success(employeePermissionVo);
        }

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("stationId", user.getStationId());
        Map<String, Object> endTimeMap = classSettlementService.queryLastEndTime(params);

        // 角色为员工标识
        boolean staff = StaffUtil.isStaff(user);
        employeePermissionVo.setStaff(staff);

        SysUser employeeShow = sysUserService.getById(user.getUserId());
        employeePermissionVo.setEmployeeShow(employeeShow.getEmployeeShow());
        // 员工权限 每次都是从上一次班结结束时间开始计算
        if (endTimeMap != null && !endTimeMap.isEmpty() && Objects.nonNull(endTimeMap.get("classEndTime"))) {
            Date endTime = (Date) endTimeMap.get("classEndTime");
            List<String> range = new ArrayList<>();
            range.add(DateUtils.dateTime(endTime));
            range.add(DateUtils.dateTime(new Date()));
            employeePermissionVo.setRange(range);
        } else {
            List<String> range = new ArrayList<>();
            range.add(DateUtils.dateTime(new Date()));
            range.add(DateUtils.dateTime(new Date()));
            employeePermissionVo.setRange(range);
        }

        return AjaxResult.success(employeePermissionVo);
    }

    @GetMapping("/newSelectStatisticsPayOrderList")
    @ApiOperation(value = "查询所有已支付订单")
    @ResponseBody
    public TableDataInfo newSelectStatisticsPayOrderList(@ApiParam(value = "油品") @RequestParam(value = "oilName", required = false) String oilName,
                                                         @ApiParam(value = "支付方式") @RequestParam(value = "payType", required = false) String payType,
                                                         @ApiParam(value = "地区") @RequestParam(value = "districtIds", required = false) String districtIds,
                                                         @ApiParam(value = "油企ID") @RequestParam(value = "enterpriseId", required = false) Long enterpriseId,
                                                         @ApiParam(value = "油站ID") @RequestParam(value = "stationId", required = false) Long stationId,
                                                         @ApiParam(value = "页面") @RequestParam Integer pageNum,
                                                         @ApiParam(value = "条数") @RequestParam Integer pageSize,
                                                         @ApiParam(value = "开始时间") @RequestParam(value = "beginTime", required = false) String beginTime,
                                                         @ApiParam(value = "结束时间") @RequestParam(value = "endTime", required = false) String endTime,
                                                         @ApiParam(value = "是否删除") @RequestParam(value = "isDeleted", required = false) String isDeleted) {

        PayOrder payOrder = new PayOrder();
        payOrder.setOilName(oilName);
        payOrder.setPayType(payType);
        payOrder.setDistrictIds(districtIds);
        payOrder.setEnterpriseId(enterpriseId);
        payOrder.setStationId(stationId);
        payOrder.setBeginTime(beginTime);
        payOrder.setEndTime(endTime);
        payOrder.setIsDeleted(isDeleted);
//        startPage();
        List<StatisticsPayOrder> payOrderList = payOrderService.newSelectStatisticsPayOrderList(payOrder);

        return getTaleDataInfo(payOrderList, pageNum, pageSize);
    }

    @GetMapping("/newSelectStatisticsPayOrderSum")
    @ApiOperation(value = "查询所有订单的金额")
    public AjaxResult newSelectStatisticsPayOrderSum(
            @ApiParam(value = "油品") @RequestParam(value = "oilName", required = false) String oilName,
            @ApiParam(value = "支付方式") @RequestParam(value = "payType", required = false) String payType,
            @ApiParam(value = "地区") @RequestParam(value = "districtIds", required = false) String districtIds,
            @ApiParam(value = "油企ID") @RequestParam(value = "enterpriseId", required = false) Long enterpriseId,
            @ApiParam(value = "油站ID") @RequestParam(value = "stationId", required = false) Long stationId,
            @ApiParam(value = "页面") @RequestParam Integer pageNum,
            @ApiParam(value = "条数") @RequestParam Integer pageSize,
            @ApiParam(value = "开始时间") @RequestParam(value = "beginTime", required = false) String beginTime,
            @ApiParam(value = "结束时间") @RequestParam(value = "endTime", required = false) String endTime,
            @ApiParam(value = "是否删除") @RequestParam(value = "isDeleted", required = false) String isDeleted

    ) {

        PayOrder payOrder = new PayOrder();
        payOrder.setOilName(oilName);
        payOrder.setPayType(payType);
        payOrder.setDistrictIds(districtIds);
        payOrder.setEnterpriseId(enterpriseId);
        payOrder.setStationId(stationId);
        payOrder.setBeginTime(beginTime);
        payOrder.setEndTime(endTime);
        payOrder.setIsDeleted(isDeleted);
        startPage();
        StatisticsPayOrder statisticsPayOrder = payOrderService.newSelectStatisticsPayOrderSum(payOrder);
        return AjaxResult.success(statisticsPayOrder);

    }

    @GetMapping("/newSelectStatisticsPayOrderListExport")
    @ApiOperation(value = "油企订单数据导出")
    public AjaxResult newSelectStatisticsPayOrderListExport(
            @ApiParam(value = "油品") @RequestParam(value = "oilName", required = false) String oilName,
            @ApiParam(value = "支付方式") @RequestParam(value = "payType", required = false) String payType,
            @ApiParam(value = "地区") @RequestParam(value = "districtIds", required = false) String districtIds,
            @ApiParam(value = "油企ID") @RequestParam(value = "enterpriseId", required = false) Long enterpriseId,
            @ApiParam(value = "油站ID") @RequestParam(value = "stationId", required = false) Long stationId,
            @ApiParam(value = "页面") @RequestParam Integer pageNum,
            @ApiParam(value = "条数") @RequestParam Integer pageSize,
            @ApiParam(value = "开始时间") @RequestParam(value = "beginTime", required = false) String beginTime,
            @ApiParam(value = "结束时间") @RequestParam(value = "endTime", required = false) String endTime
    ) {

        PayOrder payOrder = new PayOrder();
        payOrder.setOilName(oilName);
        payOrder.setPayType(payType);
        payOrder.setDistrictIds(districtIds);
        payOrder.setEnterpriseId(enterpriseId);
        payOrder.setStationId(stationId);
        payOrder.setBeginTime(beginTime);
        payOrder.setEndTime(endTime);
//        startPage();
        List<StatisticsPayOrder> payOrderList = payOrderService.newSelectStatisticsPayOrderList(payOrder);

        List<StatisticsPayOrder> payOrderListPage = payOrderList
                .stream()
                .skip((pageNum - 1) * pageSize)
                .limit(pageSize)
                .collect(Collectors.toList());

        StatisticsPayOrder statisticsPayOrder = payOrderService.newSelectStatisticsPayOrderSum(payOrder);
        statisticsPayOrder.setEnterpriseName("合计");
        payOrderListPage.add(statisticsPayOrder);
        ExcelUtil<StatisticsPayOrder> util = new ExcelUtil<>(StatisticsPayOrder.class);
        return util.exportExcel(payOrderListPage, "StatisticsPayOrder");
    }

    public String getDistrict(Integer district) {
        String districtString = "";
        switch (district) {
            case 1:
                districtString = "华北地区";
                break;
            case 2:
                districtString = "华南地区";
                break;
            case 3:
                districtString = "西南地区";
                break;
            case 4:
                districtString = "西北地区";
                break;
            case 5:
                districtString = "东北地区";
                break;
            default:
                throw new CustomException("传个正确的地区");
        }
        return districtString;
    }

    @GetMapping("/getEnterpriseByDistrict")
    @ApiOperation(value = "获取地区下的油企")
    public AjaxResult getEnterpriseByDistrict(@RequestParam(required = false) Integer district) {

        log.info("获取地区下的油企入参：{}", district);
        return AjaxResult.success(teamManagementService.getEnterpriseId(district));
    }


    @GetMapping("/getStationByEnterprise")
    @ApiOperation(value = "获取油企下的油站")
    public AjaxResult getStationByEnterprise(@RequestParam(required = false) Long enterpriseId) {

        log.info("获取油企下的油站：{}", enterpriseId);
        List<StationByEnterpriseVo> stationByEnterprise = stationService.getStationByEnterprise(enterpriseId);
        log.info("获取油站出参：{}", stationByEnterprise);
        return AjaxResult.success(stationByEnterprise);
    }


    //分页失效 手动分页
    public TableDataInfo getTaleDataInfo(List<StatisticsPayOrder> payOrderList, Integer pageNum, Integer pageSize) {
        //计算总记录数
        int total = payOrderList.size();
        //pageHelper无效，手动分页，流操作：sorted排序、skip跳记录和limit限制显示记录数
        List<StatisticsPayOrder> collect = payOrderList
                .stream()
                .skip((pageNum - 1) * pageSize)
                .limit(pageSize)
                .collect(Collectors.toList());
        //计算总页数
        int pageSum = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;
        PageHelper.startPage(pageNum, pageSize);
        PageInfo<StatisticsPayOrder> scorePageInfo = new PageInfo<>(collect);
        //总记录数
        scorePageInfo.setTotal(total);
        //总页数
        scorePageInfo.setPages(pageSum);
        //清除分页缓存
        PageHelper.clearPage();

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(collect);
        rspData.setTotal(total);
        return rspData;
    }

    @PostMapping("/handMovementPushSettleInfo")
    @ResponseBody
    public AjaxResult handMovementPushSettleInfo(@RequestBody SaasOrderVO saasOrderVO) {
        settleInfoPushService.handMovementPushSettleInfo(saasOrderVO);
        return AjaxResult.success();
    }

}
